Next Greater Element IV — LeetCode 2454 Python Solution

HardStackArrayBinary SearchSortingMonotonic StackHeap (Priority Queue)
Problem
#2454
Reading time
3 min

The problem

You are given a 0-indexed array of non-negative integers nums. For each integer in nums, you must find its respective second greater integer.

Example

Input
nums = [2,4,0,9,6]
Output
[9,6,6,-1,-1]
Explanation
0th index: 4 is the first integer greater than 2, and 9 is the second integer greater than 2, to the right of 2.

Python solution

Python
class Solution:
    def secondGreaterElement(self, nums: List[int]) -> List[int]:
        arr = [(x, i) for i, x in enumerate(nums)]
        arr.sort(key=lambda x: -x[0])
        sl = SortedList()
        n = len(nums)
        ans = [-1] * n
        for _, i in arr:
            j = sl.bisect_right(i)
            if j + 1 < len(sl):
                ans[i] = nums[sl[j + 1]]
            sl.add(i)
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2454. Next Greater Element IV is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2454. Next Greater Element IV?
LeetCode 2454. Next Greater Element IV is rated Hard on LeetCode.
What is the time complexity of LeetCode 2454. Next Greater Element IV?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 2454. Next Greater Element IV?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2454. Next Greater Element IV cover?
LeetCode 2454. Next Greater Element IV is tagged Stack, Array, Binary Search, Sorting, Monotonic Stack and Heap (Priority Queue) 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