Visualize

Pattern visualizer

Maximum and Minimum Element in an Array

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. Animated on: nums = [4,9,2,9,15,6,1,8,3] — return the largest and the smallest element..

One pass, two running extremes

time O(n)space O(1)step 1 / 10
4
[0]
9
[1]
2
[2]
9
[3]
15
[4]
6
[5]
1
[6]
8
[7]
3
[8]
line 3

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.

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

Where to practice Arrays