Next Greater Element II — LeetCode 503 Python Solution

MediumStackArrayMonotonic Stack
Problem
#503
Pattern
Stack
Reading time
3 min

The problem

Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums. The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number.

Example

Input
nums = [1,2,1]
Output
[2,-1,2]
Explanation
The first 1's next greater number is 2;

Python solution

Python
class Solution:
    def nextGreaterElements(self, nums: List[int]) -> List[int]:
        n = len(nums)
        ans = [-1] * n
        stk = []
        for i in range(n * 2 - 1, -1, -1):
            i %= n
            while stk and stk[-1] <= nums[i]:
                stk.pop()
            if stk:
                ans[i] = stk[-1]
            stk.append(nums[i])
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the length of the array nums auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 503. Next Greater Element II 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 503. Next Greater Element II?
LeetCode 503. Next Greater Element II is rated Medium on LeetCode.
What is the time complexity of LeetCode 503. Next Greater Element II?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 503. Next Greater Element II?
The Python solution on this page uses O(n), where n is the length of the array nums auxiliary space.
What topics does LeetCode 503. Next Greater Element II cover?
LeetCode 503. Next Greater Element II is tagged Stack, Array 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