SyntaxPilot
Courses/JavaScript Coding Questions/Lesson 5
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

JavaScript Coding Questions · Lesson 5 of 30

Array questions I

largest and second largest (with duplicates)min and max in one passMath.max(...arr) on 200000 items (RangeError)

These are the notes for JavaScript Coding Questions, episode 5, interview and placement practice for people who finished the SyntaxPilot JavaScript course, and the first of the array questions. Three questions: find the largest element, the second largest when there are duplicates, and the minimum and maximum together in one pass. They look easy, but the obvious answers give 0 for an all-negative array, return the topper twice, quietly reorder your data, and one built-in, Math.max(...arr), crashes with RangeError: Maximum call stack size exceeded on 200,000 items.

Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the complexity.

Every program was run with Node.js 24 (node main.js), the SyntaxPilot compiler's JavaScript command, and every output below is real. Plain modern JavaScript, no packages.

Q1: Find the largest element

Problem. Given an array of numbers, return the biggest. [3, 9, 2, 7] → 9. For an empty array there is no largest: return undefined.

Real life. A teacher finding the top score in a class of 60 walks down the register once and remembers the best mark seen so far.

Think out loud

  • One pass, keeping the best so far.
  • Edge cases: every number negative, an empty array, a huge array.

The obvious attempt: start at 0

function largest(arr) {
  let max = 0;
  for (const x of arr) if (x > max) max = x;
  return max;
}
console.log(largest([3, 9, 2, 7]), largest([-4, -2, -9]), largest([]));

Output:

9 0 0

Why it fails. Starting at 0 is a made-up guess that says "the answer is at least 0". When every number is negative, nothing beats the guess, so we return 0, which isn't even in the array. The empty array also returns 0, which hides the fact that there is no answer. Never start from a made-up value; start from a real element.

The fix

function largest(arr) {
  if (arr.length === 0) return undefined;
  let max = arr[0];
  for (const x of arr) if (x > max) max = x;
  return max;
}
console.log(largest([3, 9, 2, 7]), largest([-4, -2, -9]), largest([]));
9 -2 undefined

(Starting at -Infinity also works for non-empty arrays: every number is bigger than -Infinity.) Time O(n), space O(1).

The built-in: Math.max(...arr), and why it crashes

Math.max takes numbers as separate arguments: Math.max(3, 9, 2). To pass an array, spread it with ..., which turns each element into its own argument.

function largest(arr) {
  if (arr.length === 0) return undefined;
  let max = arr[0];
  for (const x of arr) if (x > max) max = x;
  return max;
}
console.log(largest([3, 9, 2, 7]), largest([-4, -2, -9]), largest([]));
console.log(Math.max(...[3, 9, 2, 7]), Math.max(...[-4, -2, -9]), Math.max(...[]));
const scores = Array.from({ length: 200000 }, (_, i) => (i * 7919) % 200003);
console.log(largest(scores));
console.log(Math.max(...scores));

Output:

9 -2 undefined
9 -2 -Infinity
200002
.../main.js:11
console.log(Math.max(...scores));
                 ^

RangeError: Maximum call stack size exceeded

Array.from({ length: n }, (_, i) => ...) builds an array of n items, calling the function with each index i. (i * 7919) % 200003 just scrambles the numbers so the maximum isn't at the end.

Why it crashes. Real-life picture: paying with a bag of 200,000 coins. Handing over the bag is one thing; spreading is taking every coin out and putting them into the cashier's hands one by one, and the hands overflow. A function call keeps its arguments on the call stack (the memory for calls that are running), so 200,000 separate arguments don't fit. On this machine the limit was between 125,000 and 130,000 numbers:

for (const n of [100000, 125000, 130000]) {
  const arr = new Array(n).fill(1);
  try { Math.max(...arr); console.log(n, "ok"); } catch (e) { console.log(n, e.constructor.name, e.message); }
}
100000 ok
125000 ok
130000 RangeError Maximum call stack size exceeded

The exact limit depends on the engine and the machine, so never rely on it. Math.max.apply(null, arr) is the old way of writing the same spread and has the same limit.

reduce: works at any size

const scores = Array.from({ length: 200000 }, (_, i) => (i * 7919) % 200003);
console.log(scores.reduce((a, b) => Math.max(a, b)));
console.log(scores.reduce((a, b) => (b > a ? b : a), -Infinity));
200002
200002

reduce walks the array once and keeps a running value. Without a starting value it throws on an empty array:

console.log([].reduce((a, b) => (b > a ? b : a)));
TypeError: Reduce of empty array with no initial value

so give it one (-Infinity) or check the length first.

More Math.max traps

console.log(Math.max(3, 9, 2), Math.max(...[3, 9, 2]));
console.log(Math.max([3, 9, 2]), Math.max(3, "9", 2), Math.max(3, undefined));
9 9
NaN 9 NaN
  • Math.max([3, 9, 2]): the array itself is one argument, it can't be turned into a number, so the result is NaN.
  • "9" is converted to the number 9.
  • Any undefined (or NaN) makes the whole result NaN. A hand-written b > a loop silently skips NaN instead ([3, NaN, 9] gives 9), because every comparison with NaN is false. Decide which behaviour you want.
  • Math.max() with no arguments is -Infinity (and Math.min() is Infinity): that's what spreading an empty array gives.

Q2: Find the second largest

Problem. Return the largest value that is smaller than the maximum. If there isn't one (all values equal, or fewer than two distinct values), return null.

[72, 95, 88, 95, 60] → 88     (two toppers on 95; the runner-up has 88)
[5, 5, 5]            → null
[7]                  → null

Think out loud

  • Duplicates of the top value must not count as "second".
  • Edge cases: ties at the top, all equal, one element, empty, all negative.

The obvious attempt: sort and take index 1

function secondLargest(arr) {
  const sorted = arr.sort((a, b) => b - a);
  return sorted[1];
}
const marks = [72, 95, 88, 95, 60];
console.log(secondLargest(marks));
console.log(marks);
console.log(secondLargest([5, 5, 5]), secondLargest([7]));

Output:

95
[ 95, 95, 88, 72, 60 ]
5 undefined

The compare function (a, b) => b - a returns a positive number when b is bigger, so bigger numbers go first (descending order).

Three problems.

  1. Ties. Index 1 is just the second slot. With two 95s at the top it is 95 again; [5, 5, 5] gives 5.
  2. sort changes the array in place. It doesn't make a copy: marks itself is now reordered, and sorted === marks. Any other code using marks now sees a different order (the teacher's register got rearranged).
  3. Cost. Sorting is O(n log n); one pass is O(n).

One pass: a race podium

Real-life picture: gold and silver start empty, and runners finish one at a time.

  • A new fastest runner takes gold, and the old gold holder steps down to silver.
  • A runner faster than silver only takes silver; gold stays.
  • A runner who ties with gold isn't a second place: nothing changes.
function secondLargest(arr) {
  let first = -Infinity, second = -Infinity;
  for (const x of arr) {
    if (x > first) {
      second = first;
      first = x;
    } else if (x > second && x < first) {
      second = x;
    }
  }
  return second === -Infinity ? null : second;
}
const marks = [72, 95, 88, 95, 60];
console.log(secondLargest(marks), marks);
for (const a of [[5, 5, 5], [7], [], [-3, -1, -2], [1, 2]]) {
  console.log(JSON.stringify(a), secondLargest(a));
}

Output:

88 [ 72, 95, 88, 95, 60 ]
[5,5,5] null
[7] null
[] null
[-3,-1,-2] -2
[1,2] 1
  • x < first is what skips ties with gold.
  • If second is still -Infinity at the end, no second value was ever found: return null. (-Infinity itself can't appear in normal input data.)
  • marks is untouched.

Time O(n), space O(1).

If you want the sorting version, fix it properly

const marks = [72, 95, 88, 95, 60];
const unique = [...new Set(marks)].toSorted((a, b) => b - a);
console.log(unique, unique[1] ?? null);
console.log(marks);
[ 95, 88, 72, 60 ] 88
[ 72, 95, 88, 95, 60 ]
  • A Set keeps each value only once, so the tie at the top disappears. [...set] spreads it back into an array.
  • toSorted (ES2023) returns a sorted copy and leaves the original alone. ([...arr].sort(...) does the same in older code.)
  • ??, the nullish coalescing operator, uses the right side only when the left side is null or undefined: unique[1] is undefined for [5, 5, 5], so the result is null.

Correct and short, but O(n log n) time and O(n) space. In an interview give the one-pass answer first, and mention this one.

Q3: Min and max in one pass

Problem. Return both the smallest and the largest value as { min, max }, in one pass. Empty array → null.

Real life. A weather app shows the day's lowest and highest temperature from thousands of sensor readings.

The obvious attempt: two built-in calls

const temps = Array.from({ length: 200000 }, (_, i) => (i * 7919) % 200003);
console.log("min", Math.min(...temps));
console.log("max", Math.max(...temps));
.../main.js:2
console.log("min", Math.min(...temps));
                        ^

RangeError: Maximum call stack size exceeded

The same spread crash, on the very first call. And even on a small array, two calls walk the data twice.

The fix: one loop

function minMax(arr) {
  if (arr.length === 0) return null;
  let min = arr[0], max = arr[0];
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] < min) min = arr[i];
    else if (arr[i] > max) max = arr[i];
  }
  return { min, max };
}
console.log(minMax([3, 9, 2, 7]), minMax([-4, -2, -9]), minMax([5]), minMax([]));
const temps = Array.from({ length: 200000 }, (_, i) => (i * 7919) % 200003);
console.log(minMax(temps));
console.log(Math.max(), Math.min());

Output:

{ min: 2, max: 9 } { min: -9, max: -2 } { min: 5, max: 5 } null
{ min: 0, max: 200002 }
-Infinity Infinity
  • Start both at arr[0] and loop from index 1.
  • else if: an element that just became the new min can't also be bigger than max (min ≤ max always), so the second check is skipped.
  • return { min, max } is shorthand property syntax for { min: min, max: max }.
  • The last line: Math.max() is -Infinity and Math.min() is Infinity. That's what an empty spread gives, and it can flow silently into a report. Handle the empty case first.

Time O(n), space O(1).

Bonus: fewer comparisons with pairs

The loop above can do 2 comparisons per element. Taking elements in pairs, compare the two with each other first, then only the smaller against min and the bigger against max: 3 comparisons per 2 elements, about 1.5n in total.

function minMaxPairs(arr) {
  if (arr.length === 0) return null;
  let i, min, max, comparisons = 0;
  if (arr.length % 2 === 1) { min = max = arr[0]; i = 1; }
  else { comparisons++; if (arr[0] < arr[1]) { min = arr[0]; max = arr[1]; } else { min = arr[1]; max = arr[0]; } i = 2; }
  for (; i < arr.length; i += 2) {
    let small = arr[i], big = arr[i + 1];
    comparisons++;
    if (small > big) [small, big] = [big, small];
    comparisons++; if (small < min) min = small;
    comparisons++; if (big > max) max = big;
  }
  return { min, max, comparisons };
}
const data = Array.from({ length: 1000 }, (_, i) => (i * 37) % 1009);
console.log(minMaxPairs(data), minMaxPairs([4, 1, 9]), minMaxPairs([5]));
{ min: 0, max: 1008, comparisons: 1498 } { min: 1, max: 9, comparisons: 3 } { min: 5, max: 5, comparisons: 0 }

1,498 comparisons for 1,000 elements instead of up to 1,998. Still O(n); it's a classic follow-up question, not something you need in everyday code.

Complexity summary

Question Approach Time Extra space Notes
Largest loop from arr[0] O(n) O(1) any size
Largest Math.max(...arr) O(n) O(n) on the stack RangeError past ~125,000 here
Largest reduce with -Infinity O(n) O(1) any size
Second largest sort + [1] O(n log n) O(1), but changes the array wrong with ties
Second largest Set + toSorted O(n log n) O(n) correct
Second largest podium, one pass O(n) O(1) the interview answer
Min and max two spread calls O(n), twice O(n) on the stack crashes on big arrays
Min and max one loop O(n) O(1) ≤ 2n comparisons
Min and max pairs O(n) O(1) about 1.5n comparisons

For scale, one real run on 1,000,000 numbers:

for...of: 22.388ms
reduce: 7.964ms
sort copy: 212.796ms

Sorting a copy just to find the maximum was about ten times slower than one pass.

Common mistakes (and the exact outputs)

Mistake Code What you see Why Fix
A made-up start let max = 0 [-4, -2, -9] → 0 nothing beats the guess let max = arr[0]
Forgetting empty largest([]) 0 (or -Infinity) there is no largest if (arr.length === 0) return undefined
Spreading a huge array Math.max(...scores) RangeError: Maximum call stack size exceeded every element is an argument on the stack a loop or reduce
Passing the array Math.max([3, 9, 2]) NaN an array isn't a number spread small arrays, or loop
Empty spread Math.max(...[]) -Infinity no arguments check the length first
reduce on empty [].reduce(fn) TypeError: Reduce of empty array with no initial value nothing to start from reduce(fn, -Infinity)
Sort and take [1] arr.sort((a, b) => b - a)[1] 95 for the marks ties at the top one pass, skip x === first
Sorting the caller's array arr.sort(...) marks is reordered sort works in place toSorted, or [...arr].sort
Default sort on numbers [10, 9, 1].sort() [ 1, 10, 9 ] compares as strings sort((a, b) => a - b) (episode 8)

Mini project: an exam result summary

Given each student's marks, print the topper(s), the runner-up, the lowest and the class average, in one pass.

const marks = { Asha: 72, Ravi: 95, Neha: 88, Arjun: 95, Priya: 60 };
const entries = Object.entries(marks);
let top = -Infinity, second = -Infinity, low = Infinity, sum = 0;
for (const [, m] of entries) {
  if (m > top) { second = top; top = m; }
  else if (m > second && m < top) second = m;
  if (m < low) low = m;
  sum += m;
}
const names = m => entries.filter(([, v]) => v === m).map(([n]) => n).join(", ");
console.log(`Topper(s): ${names(top)} with ${top}`);
console.log(`Runner-up: ${names(second)} with ${second}`);
console.log(`Lowest: ${names(low)} with ${low}`);
console.log(`Average: ${(sum / entries.length).toFixed(1)}`);
Topper(s): Ravi, Arjun with 95
Runner-up: Neha with 88
Lowest: Priya with 60
Average: 82.0

Object.entries turns the object into [name, mark] pairs; [, m] skips the name while destructuring. Extend it: read the marks from input, and handle an empty class.

Your turn: the third largest distinct value (solution)

Problem. Return the third largest distinct value in one pass, or null if there are fewer than three distinct values. [72, 95, 88, 95, 60] → 72, [5, 5, 4] → null.

Solution

Add bronze to the podium, and skip any value already on it:

function thirdLargest(arr) {
  let first = -Infinity, second = -Infinity, third = -Infinity;
  for (const x of arr) {
    if (x === first || x === second || x === third) continue;
    if (x > first) {
      [first, second, third] = [x, first, second];
    } else if (x > second) {
      [second, third] = [x, second];
    } else if (x > third) {
      third = x;
    }
  }
  return third === -Infinity ? null : third;
}
for (const a of [[72, 95, 88, 95, 60], [5, 5, 4], [3, 2, 1], [1, 2, 2, 3, 3, 3], [-1, -2, -3, -4], [10]]) console.log(JSON.stringify(a), thirdLargest(a));
[72,95,88,95,60] 72
[5,5,4] null
[3,2,1] 1
[1,2,2,3,3,3] 1
[-1,-2,-3,-4] -3
[10] null

The destructuring [first, second, third] = [x, first, second] moves everyone down one step at once. Time O(n), space O(1). (For the k-th largest with a big k, use sorting or a heap instead.)

Practice questions (with solutions)

1. The index of the largest element (the first one if it appears twice; -1 for empty).

Solution
function indexOfLargest(arr) {
  if (arr.length === 0) return -1;
  let best = 0;
  for (let i = 1; i < arr.length; i++) if (arr[i] > arr[best]) best = i;
  return best;
}
console.log(indexOfLargest([3, 9, 2, 9]), indexOfLargest([-5]), indexOfLargest([]));
const a = [3, 9, 2, 9];
console.log(a.indexOf(Math.max(...a)));
1 0 -1
1

Strict > keeps the first 9 (use >= for the last one). The one-liner with indexOf walks the array twice and has the spread limit.

2. The second smallest, in one pass.

Solution

The podium upside down: start at Infinity, and skip ties with the smallest.

function secondSmallest(arr) {
  let first = Infinity, second = Infinity;
  for (const x of arr) {
    if (x < first) { second = first; first = x; }
    else if (x < second && x > first) second = x;
  }
  return second === Infinity ? null : second;
}
for (const a of [[72, 95, 88, 60, 60], [5, 5], [2, 1], [7]]) console.log(JSON.stringify(a), secondSmallest(a));
[72,95,88,60,60] 72
[5,5] null
[2,1] 2
[7] null

3. The largest of each row of a 2D array (null for an empty row).

Solution
const grid = [[3, 8, 1], [-2, -7, -1], [10], []];
const rowMax = grid.map(row => row.length ? row.reduce((a, b) => (b > a ? b : a)) : null);
console.log(rowMax);
console.log([].reduce((a, b) => a + b, 0));
[ 8, -1, 10, null ]
0

map makes one answer per row; reduce without a start value uses the first element, which is why the empty row needs its own check (with a start value, reduce on [] just returns it, as the last line shows). Time O(total elements).

4. Sort a copy, leave the original alone.

Solution
const nums = [3, 9, 2, 7];
console.log(Math.max.apply(null, nums), Math.max(...nums));
console.log(nums.toSorted((a, b) => b - a), nums);
const copy = [...nums].sort((a, b) => b - a);
console.log(copy, nums);
console.log([3, NaN, 9].reduce((a, b) => (b > a ? b : a)), Math.max(3, NaN, 9));
9 9
[ 9, 7, 3, 2 ] [ 3, 9, 2, 7 ]
[ 9, 7, 3, 2 ] [ 3, 9, 2, 7 ]
9 NaN

Both toSorted and [...nums].sort leave nums as it was. The last line is a reminder: a comparison loop skips NaN, Math.max returns NaN.

Quick quiz

1. (From the video.) What does this print?

const a = [10, 9, 1];
const b = a.sort();
console.log(a, b === a);

(A) [ 10, 9, 1 ] false (B) [ 1, 9, 10 ] true (C) [ 1, 10, 9 ] true (D) [ 1, 10, 9 ] false

Answer

(C) [ 1, 10, 9 ] true. With no compare function, sort converts the items to strings and compares them as text: "1" < "10" < "9" (like words in a dictionary). And it sorts in place and returns the same array, so b === a is true. (Real output: [ 1, 10, 9 ] true.)

2. What does console.log(Math.max(), Math.min(), Math.max([])) print?

Answer

-Infinity Infinity 0. An empty array converts to the empty string, which converts to the number 0. (A one-element array [5] converts to 5; anything longer gives NaN.)

3. secondLargest([95, 95]), with the podium version: what comes back?

Answer

null. The second 95 ties with gold and is skipped, so silver stays -Infinity.

Interview questions

  1. Why is let max = 0 wrong? It invents a value; an all-negative array returns 0. Start from arr[0] (or -Infinity).
  2. Why can Math.max(...arr) throw a RangeError? Spread passes every element as a separate argument, and arguments live on the call stack; past roughly a hundred thousand elements (engine-dependent) the stack overflows. Use a loop or reduce.
  3. What is Math.max() with no arguments? -Infinity; Math.min() is Infinity.
  4. How do you find the second largest in one pass, with duplicates? Track first and second; a new max pushes first down to second; a value strictly between them becomes second; ties with first are skipped. O(n), O(1).
  5. Why not sort? O(n log n) instead of O(n), it reorders the caller's array, and index 1 is wrong with ties.
  6. What's the difference between sort and toSorted? sort changes the array and returns it; toSorted returns a new sorted array and leaves the original alone (ES2023, Node 20+).
  7. How many comparisons does min-and-max need? About 2n with the simple loop, about 1.5n by comparing in pairs. Both O(n).
  8. What does reduce without an initial value do on an empty array? Throws TypeError: Reduce of empty array with no initial value.
  9. What does ?? do, and how is it different from ||? a ?? b gives b only if a is null or undefined; a || b gives b for any falsy a, including 0 and "". For a mark of 0, ?? keeps the 0.

Glossary

Term Meaning Example
Array An ordered list of values, indexed from 0 [3, 9, 2, 7]
Index The position of an element, starting at 0 arr[0] is 3
One pass Visiting each element exactly once the for...of loop
for...of A loop over the values of an array for (const x of arr)
Infinity / -Infinity Numbers bigger / smaller than every other number -Infinity < -1e308
Math.max / Math.min The largest / smallest of their arguments Math.max(3, 9) is 9
Argument A value passed to a function 3 and 9 above
Spread syntax (...) Expands an array into separate items Math.max(...arr)
Call stack The memory holding the function calls that are running, with their arguments overflowed by 200,000 arguments
RangeError An error for a value outside the allowed range Maximum call stack size exceeded
NaN "Not a Number" Math.max([3, 9, 2])
Array.from Builds an array from a length and a function Array.from({ length: 3 }, (_, i) => i) is [0, 1, 2]
reduce Combines all elements into one value with a running result arr.reduce((a, b) => a + b, 0)
Initial value The starting running value of reduce -Infinity
sort Sorts an array in place and returns it; strings by default [10, 9, 1].sort() is [1, 10, 9]
In place Changing the original data instead of making a copy sort, reverse
Compare function Tells sort the order: negative = a first, positive = b first (a, b) => b - a (descending)
toSorted Returns a sorted copy (ES2023) nums.toSorted((a, b) => a - b)
Set A collection that holds each value once new Set([95, 95]) has one item
Nullish coalescing (??) Right side only if the left is null or undefined undefined ?? null is null
Shorthand property { min } means { min: min } return { min, max }
Destructuring Unpacking arrays or objects into variables [first, second] = [x, first]
Object.entries An object's [key, value] pairs as an array [["Asha", 72], ...]
Distinct Different from each other (duplicates counted once) 3 distinct values in [5, 5, 4, 1]
Edge case An input at the boundary that often breaks code [], [7], all negative, ties
O(n) Work grows in proportion to the array length one pass
O(n log n) The cost of sorting toSorted
O(1) space A fixed number of extra variables first, second

Summary

  • Largest: start from arr[0], never from 0; handle the empty array first. O(n) time, O(1) space.
  • Math.max(...arr) passes every element as an argument and crashes on huge arrays (RangeError: Maximum call stack size exceeded, past about 125,000 here). Math.max(arr) is NaN, Math.max() is -Infinity. For big arrays use a loop or reduce with a starting value.
  • Second largest: a podium in one pass; a new gold pushes the old gold to silver, ties with gold are skipped; null if there is no second. O(n), O(1).
  • sort changes the array in place (and sorts as strings by default); toSorted returns a copy.
  • Min and max: one loop from arr[0] with if / else if; about 1.5n comparisons if you compare in pairs.
  • Always test: all negative, ties at the top, one element, empty, and a huge array.

Next episode: Array questions II: reverse an array in place, rotate it by k (the reversal trick, and k larger than n), and remove duplicates (Set vs filter + indexOf, O(n) vs O(n²)).