Next Greater Element I — LeetCode 496 Python Solution

EasyStackArrayHash TableMonotonic Stack
Problem
#496
Pattern
Stack
Reading time
2 min

The problem

The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.

Example

Input
nums1 = [4,1,2], nums2 = [1,3,4,2]
Output
[-1,3,-1]
Explanation
The next greater element for each value of nums1 is as follows:

Python solution

Python
class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        stk = []
        d = {}
        for x in nums2[::-1]:
            while stk and stk[-1] < x:
                stk.pop()
            if stk:
                d[x] = stk[-1]
            stk.append(x)
        return [d.get(x, -1) for x in nums1]

Complexity

MeasureComplexity
TimeO(m + n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 496. Next Greater Element I is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 496. Next Greater Element I?
LeetCode 496. Next Greater Element I is rated Easy on LeetCode.
What is the time complexity of LeetCode 496. Next Greater Element I?
The Python solution on this page runs in O(m + n).
What is the space complexity of LeetCode 496. Next Greater Element I?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 496. Next Greater Element I cover?
LeetCode 496. Next Greater Element I is tagged Stack, Array, Hash Table and Monotonic Stack on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview