Next Greater Element I

Easy

Topics
ArrayHash TableStackMonotonic Stack

a is a subset of b, and all values in both arrays are distinct.

For each value in a, find where it occurs in b and report the first value to the right of it in b that is greater than it. If there is no such value, report -1.

Return the answers in the same order as a.

Example 1

a401122
b10314223
answer-13-1
has a greater value to its right in bnothing greater to its right
Each value of a is looked up in b, and the answer is the first value to the right of it in b that is larger — position in b is what matters, not position in a. Here 2 values have nothing larger after them, which is what the -1s mark.
The two rows are the two input arrays; they have independent lengths.
Input:  a = [4,1,2], b = [1,3,4,2]
Output: [-1,3,-1]
Explanation: Nothing right of 4 in b is bigger. Right of 1 comes 3. Right of 2 there is nothing at all.

Example 2

a2041
b10213243
answer3-1
has a greater value to its right in bnothing greater to its right
Input:  a = [2,4], b = [1,2,3,4]
Output: [3,-1]
Explanation: 3 follows 2; 4 is last in b.

Example 3

a10
b10
answer-1
nothing greater to its right
Input:  a = [1], b = [1]
Output: [-1]
Explanation: A single element has nothing to its right.

Constraints

  • 1 <= a.length <= b.length <= 1000
  • 0 <= a[i], b[i] <= 10^4
  • All values in a and b are unique
  • Every value in a also appears in b
Editorial — intuition, approach, complexity and pitfalls

Intuition

The brute force is to locate each value in b and then scan rightwards for something larger, which re-walks the same tail of b over and over.

The observation that removes the rescanning: process b once, left to right, holding the values whose answer is still unknown. When a new value arrives it is the answer for every held value smaller than it — and it answers them in order, because the held values are necessarily in decreasing order. A value can only be waiting if everything that came before it and was smaller has already been answered.

So the holding structure is a stack that never contains an increasing pair, and each value is pushed once and popped once. The answers come out as b is scanned, independently of a, so the last step is a lookup.

Approach

  1. Keep a stack of values from b whose next-greater is not yet known, and a map from value to answer.
  2. Scan b. While the stack is non-empty and its top is smaller than the current value, pop it and record the current value as its answer.
  3. Push the current value. Anything left on the stack at the end has no greater value to its right.
  4. Read the answers for a out of the map, defaulting to -1 for values still on the stack.

Walkthrough

b = [1, 3, 4, 2]

value   stack before   pops and answers        stack after
  1     []             --                      [1]
  3     [1]            1 -> 3                  [3]
  4     [3]            3 -> 4                  [4]
  2     [4]            4 is bigger, no pop     [4, 2]

left on the stack: 4 and 2, so both answer -1
map: {1: 3, 3: 4, 4: -1, 2: -1}

a = [4, 1, 2]  ->  [-1, 3, -1]

Complexity

  • Time — O(n + m): every element of b is pushed once and popped at most once, then one lookup per element of a. The nested scan is O(n * m).
  • Space — O(m): the stack and the answer map, both bounded by the size of b.

Common Pitfalls

  • Searching the whole of b rather than only the part to the right of the value’s own position. The first greater value anywhere is not the answer.
  • Keeping the stack in increasing order. It has to be decreasing from the bottom, which is what the pop loop maintains.
  • Forgetting the values still on the stack at the end. They are exactly the ones with no answer, and they need -1.
  • Using <= in the pop test. The values are distinct so it makes no difference here, but it does in the variants where they are not.

Full Solution — all languages

class Solution:
    def nextGreaterElement(self, a, b):
        answer = {}
        stack = []
        for value in b:
            while stack and stack[-1] < value:
                answer[stack.pop()] = value
            stack.append(value)
        return [answer.get(value, -1) for value in a]
SensAI
Beta
Tap the mic to stop voice mode