Min and Max in Array
One pass, two running extremes
Both answers fall out of a single walk. Hold two candidates, mx and mn, seeded with the first element, and compare every later element against them. Seeding from the array itself is what makes this safe for negative-only or positive-only inputs, where a hardcoded starting constant would silently be wrong. Once an element loses a comparison it can never win later, so nothing needs revisiting and no second pass — or sort — is required.
Details
Animated on: nums = [4,9,2,9,15,6,1,8,3] — return the largest and the smallest element.
Problem:Min and Max in ArrayEasy
One pass, two running extremes
step 1 / 10
Both mx and mn start at nums[0]=4: with a single element seen, it is at once the largest and the smallest. Seeding from 0 or from a made-up "very large" constant is the classic bug — an all-negative array would report a maximum it never contains.
- mx=0· arr[0] = 4
- mn=0· arr[0] = 4
1FUNCTION maxAndMin(nums)2 mx <- nums[0]3 mn <- nums[0]4 FOR i <- 1 TO LENGTH(nums) - 15 IF nums[i] > mx6 mx <- nums[i]7 IF nums[i] < mn8 mn <- nums[i]9 RETURN mx, mn
← / → step · space play · Home restart
Every step in words
Show all 10 steps
- Both mx and mn start at nums[0]=4: with a single element seen, it is at once the largest and the smallest. Seeding from 0 or from a made-up "very large" constant is the classic bug — an all-negative array would report a maximum it never contains.
- nums[1]=9 beats the running maximum 4, so mx moves here. Every earlier element was already compared and lost, so none of them can ever win again.
- nums[2]=2 undercuts the running minimum 4, so mn moves here.
- nums[3]=9 only ties the running maximum, and the test is strictly greater, so nothing moves — a repeated largest value cannot change the answer, and keeping the first one makes the scan deterministic.
- nums[4]=15 beats the running maximum 9, so mx moves here. Every earlier element was already compared and lost, so none of them can ever win again.
- nums[5]=6 does not beat 15 and does not undercut 2, so neither extreme changes. A single pass never has to remember the middle values, only the two ends.
- nums[6]=1 undercuts the running minimum 2, so mn moves here.
- nums[7]=8 does not beat 15 and does not undercut 1, so neither extreme changes. A single pass never has to remember the middle values, only the two ends.
- nums[8]=3 does not beat 15 and does not undercut 1, so neither extreme changes. A single pass never has to remember the middle values, only the two ends.
- The scan is over after 8 comparisons against each extreme: maximum 15 at index 4, minimum 1 at index 6. Sorting first would answer the same question in O(n log n) — one pass is strictly cheaper.
Now solve it yourself
Watching is the first half. The second is writing it without the animation.