The brute force checks every element against all elements to its right, O(n²). The answer they want is one pass from the right, carrying the largest value seen so far: an element is a leader exactly when it's greater than that maximum. That's O(n) time and O(1) extra space; collect right to left, then reverse to report in input order. Pin down the edge cases out loud: the last element is always a leader, and with "greater than" (not "greater or equal") a value equal to one on its right isn't. The general version of this idea is a monotonic stack for "next greater element".
Find the leaders in an array (every element greater than all elements to its right).
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
For each element, scan everything to its right and stop at the first value that is greater or equal. It's correct and a fine first thing to say, but it's O(n²) comparisons.
// An element is a leader when it is greater than every element to its right.// Check each one against everything after it: O(n²).function leaders(xs) {const out = [];for (let i = 0; i < xs.length; i++) {let isLeader = true;for (let j = i + 1; j < xs.length; j++) {if (xs[j] >= xs[i]) {isLeader = false;break;}}if (isLeader) out.push(xs[i]);}return out;}
passes 3 checks run on every build, against the native method where there is one
- finds the leaders, in order
- the last element is always a leader; equal values are not
- sorted inputs
Walking from the end, the maximum of everything to the right is known at each step, so the test is a single comparison: x > maxRight. Start maxRight at -Infinity so the last element counts and negative numbers work. The first check compares with the brute-force definition on 300 random arrays, duplicates included.
// One pass from the right, remembering the largest value seen so far: O(n) time, O(1) extra.function leaders(xs) {const out = [];let maxRight = -Infinity;for (let i = xs.length - 1; i >= 0; i--) {if (xs[i] > maxRight) {out.push(xs[i]);maxRight = xs[i];}}return out.reverse(); // found right to left; report in input order}
passes 3 checks run on every build, against the native method where there is one
- same answers as the definition, on 300 random arrays
- linear time: a million elements in one pass
- negative numbers
Keep a stack of indexes whose values decrease from bottom to top; each new value pops every smaller value it beats and becomes their "next greater element". Every index is pushed and popped at most once, so it's O(n). Leaders are among the indexes left without a greater element; the strict version also excludes values with an equal one to the right. The same stack solves stock spans, daily temperatures, and "buildings with an ocean view" (which is leaders by index).
// The general tool: a monotonic stack gives every element's next greater element to its right in// O(n). Leaders are exactly the elements that have none.function nextGreaterToRight(xs) {const result = new Array(xs.length).fill(-1); // -1: nothing greater to the rightconst stack = []; // indexes still waiting for a greater value; their values decrease downwardfor (let i = 0; i < xs.length; i++) {while (stack.length && xs[stack[stack.length - 1]] < xs[i]) result[stack.pop()] = i;stack.push(i);}return result;}// Leaders by "greater than or equal to everything on the right" are those with no strictly// greater element; strict leaders also need no equal one, which the right-to-left scan handles.function leaderIndexes(xs) {const out = [];let maxRight = -Infinity;for (let i = xs.length - 1; i >= 0; i--) {if (xs[i] > maxRight) {out.push(i);maxRight = xs[i];}}return out.reverse();}
passes 3 checks run on every build, against the native method where there is one
- next greater element to the right
- elements with no greater element to the right include every leader
- buildings with an ocean view to the right
Buildings with a view
"Which buildings can see the ocean to the right?" is leaders by index, and a common phone-screen variant.
Running maximum in charts
Marking all-time highs in a price series is the same scan in the other direction: a value is a new high when it beats the running maximum so far.
Monotonic stacks in UI
Finding, for each element, the next taller element to its right is how layouts compute which items are hidden behind others in a row.
Starting the running maximum at 0, which breaks on all-negative arrays.
Using
>=where the definition says greater than, so equal values are counted as leaders.Forgetting to reverse, and returning leaders in right-to-left order.
Math.max(...xs.slice(i + 1))inside a loop: stillO(n²), and spreading a large slice can exceed the argument limit.
What if leaders are defined as greater than all elements to the left?
Scan from the left with a running maximum; no reversal needed. That's the "record highs" problem.
How would you find leaders in a stream that grows on the right?
A new element removes every current leader smaller than or equal to it and is itself a leader: a monotonic stack, amortised O(1) per element.
What's the space complexity of the right-to-left scan?
O(1) extra beyond the output, which can be up to n (a strictly decreasing array is all leaders).