#503

Next Greater Element II

Medium Monotonic stack, circular

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

The array is circular. For each element, return the next greater element when searching forward (wrapping around), or -1.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: next greater element in a circular array.

Why this works: loop twice; the second lap only answers items still waiting.

Example: [1, 2, 1]

2 answers the first 1second lap: 2 answers the last 1; 2 itself → -1[2, -1, 2]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Pushing during the second pass too, which can record wrong answers and wastes work.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(n).
Topic: Stack & Queue
🎬 Episodes 46–52: video coming soon