Skip to content

Next Greater Element I

For each query value, find the first larger value to its right in another array, with one stack pass.

EasyStacks
Solve on LeetCode

The problem

You get two arrays of distinct integers, nums1 and nums2, and every value of nums1 also appears somewhere in nums2. For each value of nums1, find where it sits in nums2 and look to its right for the first value that is larger. Return those larger values in the order of nums1, using -1 when nothing to the right is larger.

Input nums1 = [6, 2], nums2 = [2, 7, 6, 1, 8]

Output [8, 7]

To the right of 6 in nums2, 1 is smaller and 8 is the first larger value. Right after 2 comes 7, which is already larger.

Input nums1 = [9, 3, 5], nums2 = [3, 5, 9]

Output [-1, 5, 9]

9 is the last value of nums2, so nothing to its right can be larger.

Key constraint: Both arrays are small (up to 1,000 values), so O(m * n) passes, but the follow-up asks for O(m + n).

How to spot the pattern

  • For each element you need the first larger value to its right.
  • The question is about the nearest element in one direction that beats the current one.
  • The follow-up asks for linear time.

The idea

Walk through nums2 and keep a stack of the values that are still waiting for something larger; from bottom to top they are decreasing. When a new value arrives, it is the answer for every smaller value on top of the stack, so pop those and record the answer in a map. Values still on the stack at the end never found anything larger, and each query from nums1 becomes a single map lookup.

Brute force: For each value in nums1, find it in nums2 and scan to the right, which takes O(m * n) time.

Step by step

  1. 1Create an empty stack and an empty map from a value to its next greater value.
  2. 2For each value x in nums2, pop every stack value smaller than x and map it to x.
  3. 3Push x, since it is now waiting for its own next greater value.
  4. 4For each value in nums1, return its entry from the map, or -1 if it has none.

See the pattern move

The stacks pattern on a small example. Step through it, or press play.

Code

class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        next_greater = {}  # value -> first larger value to its right in nums2
        stack = []  # values still waiting, decreasing from bottom to top
        for x in nums2:
            while stack and stack[-1] < x:
                next_greater[stack.pop()] = x
            stack.append(x)
        return [next_greater.get(x, -1) for x in nums1]

Complexity

Time

O(m + n)

Space

O(n)

Each value of nums2 is pushed and popped at most once; the stack and the map hold at most n values.

Watch out for

  • Popping while the top is larger than x instead of smaller, which builds the wrong kind of stack and records the wrong answers.
  • Storing answers by position in nums2 and then reading them with positions from nums1; the two arrays only line up by value.

Follow-up questions

What if the array is circular, so the search can wrap around to the start?

Loop over the array twice using index i % n, and only push indexes during the first pass. The second pass gives the values near the end a chance to find a larger value at the start. That is Next Greater Element II.

What if you need the distance to the next greater value instead of the value itself?

Push indexes instead of values. When index j is popped while you are at index i, its answer is i - j. That is Daily Temperatures.

In Hinglish

Stack mein woh numbers rakho jinko abhi tak bada number nahi mila. Naya bada number aaye toh woh un sabka answer hai, unhe pop karke map mein likh do.

Related problems