Next Larger Element

easy

Given an array arr, for each element find the next greater element to its right — the first element further right that is strictly greater. If there is none, use -1.

Return an array of these next-greater values, one per position.

Hints

Scanning right from each element is O(n^2) — can you reuse comparisons?
Sweep right to left, keeping a stack that stays decreasing.
Pop everything <= the current element; the remaining top is its next greater.

Common doubts

The next-greater element lies to the right, so processing right first means the relevant candidates are already on the stack when you reach index i.
Once arr[i] sits to their left, a smaller-or-equal stacked value can never be the next-greater of anything further left — arr[i] blocks it. So it's useless.
Each element is pushed once and popped at most once over the whole run, so the total pop work is O(n) — the inner loop is amortized O(1).

Interview follow-ups

Keep an increasing stack and pop elements >= the current one; the same template, flipped.
Iterate the indices twice (mod n) so elements can wrap around to find a greater element earlier in the array — that's Next Greater Element II.

Fun facts

  • The monotonic stack is the workhorse behind next/previous greater/smaller — and, through those, histogram and subarray-domination problems.
  • The amortized 'each element pops once' argument is the same accounting used for the two-stack queue.

Asked at

AmazonFlipkartMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: arr = [1, 3, 2, 4]
Output: [3, 4, 4, -1]
Next greater to the right of 1 is 3; of 3 is 4; of 2 is 4; of 4 there is none (-1).
Example 2
Input: arr = [6, 8, 0, 1, 3]
Output: [8, -1, 1, 3, -1]
8 has no greater element to its right, and neither does the last 3.
Constraints

- 1 <= arr.length <= 10^6 - 1 <= arr[i] <= 10^9

Solve this problem →