Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Next Greater Element

Stacksmedium

Implement `nextGreaterElement(nums)` returning, for each element, the next greater value to its right, or `-1` if none, using a monotonic stack.

Sample tests

Input: nextGreaterElement([2,1,3])
Output: [3,3,-1]
Input: nextGreaterElement([1,2,3])
Output: [2,3,-1]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Storing values instead of indices makes it hard to record the answer.

Learning resources

  • Wikipedia: Data structure
Approach & explanation (try first)

A monotonic stack of indices resolves each element's next-greater value in O(n) time.

Loading...
⌘/Ctrl + Enter

Run your code to see results.