Next Greater Element I (LeetCode 496): Solution and Explanation

Easy
Array
Hash Table
Stack
Monotonic Stack

For each value of nums1, find the same value in nums2 and return the first larger value to its right there, or -1 if there is none. All values are distinct and nums1 is a subset of nums2.

Intuition

The answers only depend on nums2. If you knew the next greater element of every value in nums2, each query from nums1 would be a single hash map lookup.

While scanning nums2, some earlier values have not met anything larger yet. They must be in decreasing order: if a smaller value sat below a larger one, the larger one would already have been its answer. So the waiting values form a decreasing stack.

When a new value arrives, it is the answer for every waiting value smaller than it, and those are exactly the values on top of the stack. Pop them, record the answer, then push the new value so it can wait for its own answer.

Approach: Monotonic stack + hash map

  1. Create an empty map next_greater and an empty stack.
  2. For each num in nums2: while the stack is not empty and its top is smaller than num, pop the top and set next_greater[top] = num.
  3. Push num onto the stack.
  4. Values still on the stack after the scan have no larger value to their right.
  5. Return next_greater.get(x, -1) for each x in nums1.

Step-by-step example

nums1 = [4,1,2], nums2 = [1,3,4,2]
  1. Read 1. The stack is empty, so push it. Stack: [1].
  2. Read 3. The top 1 is smaller, so pop it and record 1 → 3. Push 3. Stack: [3].
  3. Read 4. The top 3 is smaller, so pop it and record 3 → 4. Push 4. Stack: [4].
  4. Read 2. The top 4 is larger, so nothing pops. Push 2. Stack: [4, 2].
  5. 4 and 2 never found a larger value. Answer the queries: 4 → -1, 1 → 3, 2 → -1, giving [-1,3,-1].

Code: Python, Java, C++

1class Solution:
2    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
3        next_greater = {}
4        stack = []
5        for num in nums2:
6            while stack and stack[-1] < num:
7                next_greater[stack.pop()] = num
8            stack.append(num)
9        return [next_greater.get(x, -1) for x in nums1]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m + n)

Each value of nums2 is pushed once and popped at most once, so the scan is O(n). Each of the m queries is one O(1) lookup.

Space

O(n)

The stack and the map each hold at most n values of nums2.

Other approaches

Brute force (time O(m * n), space O(1))

For each query, find its position in nums2 and scan right until a larger value appears. Simple, and fine for the small limits, but quadratic in the worst case.

Scan right to left (time O(m + n), space O(n))

Walk nums2 from the right with a stack of candidates. Pop everything not larger than the current value; the remaining top is its answer. Then push the current value. It is the same monotonic stack seen from the other side.

Common mistakes

  • Searching nums2 for each query. That works but misses the O(m + n) follow-up.
  • Using <= in the pop condition. Values are distinct here, but in variants with duplicates an equal value is not greater and must not resolve the top.
  • Forgetting the default. Values left on the stack have no entry in the map, so the lookup must fall back to -1.
  • Storing answers by index of nums2 and then looking up by value. Either key by value (allowed because values are distinct) or map each value to its index first.

Frequently asked questions

Why is the stack always decreasing?

A value is pushed only after every smaller value on top has been popped. So each value sits on top of something larger, and the stack decreases from bottom to top.

Why is this O(n) when there is a loop inside a loop?

The inner while loop pops, and each value can be popped only once over the whole scan. The total work across all iterations is at most n pops plus n pushes.

Why can the map be keyed by value?

All values in nums2 are distinct, so each value identifies one position. With duplicates you would key by index instead, as in Daily Temperatures.

How does this relate to Next Greater Element II?

Next Greater Element II uses the same monotonic stack on a circular array. You scan the array twice, using indices modulo n, so values near the end can find answers at the start.