Return both the smallest and largest numbers of a list in a single loop as a tuple. Learn why one pass beats calling min() and max() separately.
The problem
Return a tuple (smallest, largest) from a non-empty list in one loop.
Examples
Example 1
Input
min_max([3, 9, 2, 7])
Expected output
(2, 9)
Example 2
Input
min_max([5])
Expected output
(5, 5)
+ 2 hidden tests on Submit.
Edge cases to ask about
- Single element
- All equal
Hints
0/3How an interviewer scores this
0/9Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.
Complexity Lab
What does this cost as n grows?
Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and measure your code against the optimal one at growing input sizes.
Pick both to reveal the answer.
Measure it
Runs the function on inputs of size 250 up to 16,000 and records the time and peak memory. Slow solutions stop early — a short curve is itself the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| min() then max() | O(n) | O(1) | Two passes, 2n comparisons. |
| bestOne loop | O(n) | O(1) | Same Big-O; one pass matters for streams. |
Walkthrough of the optimal approach (try it yourself first)
Initialise both to the first element and update them in one loop. min() + max() is also O(n) — Big-O hides constant factors — but one pass matters when the data is a stream you can only read once.
Complexity: O(n) time, O(1) space. One pass; two variables.
Reveal the reference solution
def min_max(nums): lo = hi = nums[0] for x in nums[1:]: if x < lo: lo = x elif x > hi: hi = x return lo, hi
Follow-ups interviewers ask
- Do it with about 1.5n comparisons (compare in pairs).
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of Find Min and Max in One Pass in Python?
The optimal solution runs in O(n) time and O(1) auxiliary space. One pass; two variables.
What is the brute-force approach, and how do you optimise it?
min() then max(): O(n) time, O(1) space. Two passes, 2n comparisons. One loop: O(n) time, O(1) space. Same Big-O; one pass matters for streams.
What follow-up questions do interviewers ask about Find Min and Max in One Pass?
Do it with about 1.5n comparisons (compare in pairs).
