Understanding Next Greater Element
For each value in nums, return the first strictly greater value to its right, or -1 when none exists.
How it works
Scanning from right to left lets a decreasing stack discard dominated candidates.
Scan indices from right to left. Pop candidates no larger than the current value. Read the remaining top as the answer, then push the current value.
Try an example
Input: nums = [2, 1, 2, 4, 3]
Output: [4, 2, 4, -1, -1]
Scanning from right to left lets a decreasing stack discard dominated candidates.
Constraints
- 0–64 integers between -1,000,000 and 1,000,000.
- Equal values do not count as greater.
Use the simulator
Change the input, then choose Visualize input. Use Next and Previous to inspect each decision, or Play to advance automatically. Compare approaches and their complexity. Choose Try yourself to write JavaScript, select My code and Visualize code to inspect its execution, or Run Tests to check results.
Execution happens in your browser. Drafts are saved locally; avoid entering secrets or sensitive information.