Find max and min in one pass

Track both values in a single loop: start with the first element as both min and max, then compare each remaining element against both; this is O(n) time and O(1) space and avoids spreading huge arrays into Math.min/Math.max.

Why not Math.max(...arr)?

It is fine for small arrays, but:

  • It walks the array twice (once for min, once for max).
  • Spreading a very large array (hundreds of thousands of elements) can exceed the engine's argument limit and throw a RangeError.
  • On an empty array, it returns -Infinity/Infinity, which may hide a bug.

Details to handle

  • Empty input: return undefined/null or throw, and document which.
  • NaN: Math.max returns NaN if any element is NaN; a manual loop with </> silently ignores it. Decide which behaviour you want.
  • Objects: compare by a key (find the cheapest product, the latest event) and return the whole object.
  • Pairwise comparison trick: comparing elements in pairs first, then the smaller with min and the larger with max, uses about 1.5n comparisons instead of 2n. Mention it as an optimisation.

Related

  • reduce version: concise, same complexity.
  • Second largest: track the top two values in one pass.

Code example

js
1function minMax(arr) {
2 if (arr.length === 0) return null;
3 let min = arr[0];
4 let max = arr[0];
5 for (let i = 1; i < arr.length; i++) {
6 const v = arr[i];
7 if (v < min) min = v;
8 else if (v > max) max = v;
9 }
10 return { min, max };
11}
12
13console.log(minMax([7, 2, 9, -4, 5])); // { min: -4, max: 9 }
14console.log(minMax([42]), minMax([])); // { min: 42, max: 42 } null
15
16// Large arrays: spreading can throw, the loop cannot
17const big = Array.from({ length: 300_000 }, (_, i) => (i * 7919) % 300_000);
18try {
19 Math.max(...big);
20 console.log("spread worked here");
21} catch (e) {
22 console.log("spread failed:", e.name); // RangeError in some engines
23}
24console.log(minMax(big)); // { min: 0, max: 299999 }
25
26// By key, returning the whole object
27function minMaxBy(items, key) {
28 if (!items.length) return null;
29 return items.reduce(
30 (acc, item) => ({
31 min: item[key] < acc.min[key] ? item : acc.min,
32 max: item[key] > acc.max[key] ? item : acc.max,
33 }),
34 { min: items[0], max: items[0] }
35 );
36}
37const products = [{ name: "Pen", price: 2 }, { name: "Laptop", price: 1200 }, { name: "Book", price: 15 }];
38const { min, max } = minMaxBy(products, "price");
39console.log(min.name, max.name); // Pen Laptop
40
41// Second largest in one pass
42const secondLargest = (arr) => {
43 let first = -Infinity, second = -Infinity;
44 for (const v of arr) {
45 if (v > first) [first, second] = [v, first];
46 else if (v > second && v < first) second = v;
47 }
48 return second === -Infinity ? null : second;
49};
50console.log(secondLargest([5, 9, 9, 3, 7])); // 7

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app