#503
Next Greater Element II
MediumArrayStackMonotonic StackMonotonic StackCircular Array
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)
Using a monotonic stack allows us to efficiently find the next greater element for each number in a single pass. We can simulate the circular nature by doubling the array.
⚙️
Algorithm
3 steps- 1Step 1: Create a stack to keep track of indices and an output array initialized to -1.
- 2Step 2: Traverse the array twice (to account for circularity) using the modulo operator.
- 3Step 3: For each element, while the stack is not empty and the current element is greater than the element at the index stored in the stack, pop from the stack and set the output for that index.
solution.py10 lines
1def nextGreaterElements(nums):
2 n = len(nums)
3 output = [-1] * n
4 stack = []
5 for i in range(2 * n):
6 while stack and nums[stack[-1]] < nums[i % n]:
7 output[stack.pop()] = nums[i % n]
8 if i < n:
9 stack.append(i)
10 return outputℹ
Complexity note: This complexity is efficient because we only pass through the array twice, and each element is pushed and popped from the stack at most once.
- 1Using a stack helps manage the order of elements efficiently.
- 2Circular arrays can be handled by simulating a longer array.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.