Two things at once
Track the smallest and the largest in one pass. About 6 minutes.
One walk, two facts
A weather app shows today's low and high. It doesn't scan the day's readings twice: it looks at each reading once and checks both things as it goes.
You can do the same. Keep two variables, the lowest so far and the highest so far, and update both at every box. One loop, two answers.
low = 4, high = 4.
Both start at the first box
Before you've seen anything else, the first value is both the lowest and the highest so far. So start both variables there, for the same reason as last time: it's always a real value.
Use two separate checks, one for "lower?" and one for "higher?". A value can only change one of them, but you have to ask both questions.
low = high = nums[0]
for x in nums:
if x < low:
low = x
if x > high:
high = x
return [low, high]After one walk over 5, 5, 2, 8, what are the lowest and highest so far?
- ALowest 2, highest 8
- BLowest 5, highest 8
- CLowest 8, highest 2
Show the answer
Lowest 2, highest 8. 2 is the smallest and 8 the largest, both found in the same walk.
Smallest and largest
You get a list with at least one number. Return [smallest, largest], using one pass over the list.
nums = [4, 1, 7, 3] → [1, 7]
1 ≤ n ≤ 1,000