Next Greater Element II — Circular Array Monotonic Stack
Advertisement
Problem 263 · Next Greater Element II
Difficulty: Medium · Pattern: Circular Monotonic Stack
Circular array — wrap around once.
Solutions
# Python
def nextGreaterElements(nums):
n = len(nums); res = [-1]*n; stack = []
for i in range(2*n):
while stack and nums[stack[-1]] < nums[i%n]:
res[stack.pop()] = nums[i%n]
if i < n: stack.append(i)
return res
// Java
public int[] nextGreaterElements(int[] nums) {
int n = nums.length; int[] res = new int[n]; Arrays.fill(res, -1);
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < 2*n; i++) {
while (!stack.isEmpty() && nums[stack.peek()] < nums[i%n])
res[stack.pop()] = nums[i%n];
if (i < n) stack.push(i);
}
return res;
}
// C++
vector<int> nextGreaterElements(vector<int>& nums) {
int n = nums.size(); vector<int> res(n,-1); stack<int> st;
for (int i = 0; i < 2*n; i++) {
while (!st.empty() && nums[st.top()] < nums[i%n])
res[st.top()]=nums[i%n], st.pop();
if (i < n) st.push(i);
}
return res;
}
Complexity
- Time: O(n)
- Space: O(n)
Advertisement