DSA Tracker

Visualize

Min and Max in Array

One pass, two running extremes

time O(n)space O(1)

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

4
[0]
9
[1]
2
[2]
9
[3]
15
[4]
6
[5]
1
[6]
8
[7]
3
[8]

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
Pseudocode
1FUNCTION maxAndMin(nums)
2 mx <- nums[0]
3 mn <- nums[0]
4 FOR i <- 1 TO LENGTH(nums) - 1
5 IF nums[i] > mx
6 mx <- nums[i]
7 IF nums[i] < mn
8 mn <- nums[i]
9 RETURN mx, mn

← / → step · space play · Home restart

Every step in words

Show all 10 steps
  1. 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.
  2. 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.
  3. nums[2]=2 undercuts the running minimum 4, so mn moves here.
  4. 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.
  5. 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.
  6. 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.
  7. nums[6]=1 undercuts the running minimum 2, so mn moves here.
  8. 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.
  9. 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.
  10. 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.