#2454
Next Greater Element IV
HardArrayBinary SearchStackSortingHeap (Priority Queue)Monotonic StackStackArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a stack to efficiently track the first and second greater elements while iterating through the array only once. This reduces the time complexity significantly.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an empty stack to keep track of indices and an array for the result.
- 2Step 2: Iterate through the nums array from right to left, maintaining a stack of indices where we have not yet found a second greater element.
- 3Step 3: For each element, pop elements from the stack until we find the first greater element, then check the next element in the stack for the second greater element.
solution.py11 lines
1def secondGreater(nums):
2 n = len(nums)
3 result = [-1] * n
4 stack = []
5 for i in range(n - 1, -1, -1):
6 while stack and nums[stack[-1]] <= nums[i]:
7 stack.pop()
8 if stack:
9 result[i] = nums[stack[-1]]
10 stack.append(i)
11 return resultℹ
Complexity note: The time complexity is O(n) because we traverse the nums array once and each element is pushed and popped from the stack at most once. The space complexity is O(n) due to the stack used to store indices.
- 1Using a stack helps keep track of indices efficiently.
- 2Iterating from the end allows us to find the second greater element without re-scanning the array.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.