503. Next Greater Element II
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to find the "next greater element" for each number in a circular integer array. A circular array means that the element after the last element is the first element. The next greater element for a number x is the first number that is larger than x when traversing the array in order. If no such number exists, we should use -1.
Solution
Next Greater Element II in Python
class Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:
n = len(nums)
result = [-1] * n # Initialize result list with -1
stack = [] # Stack to store indices
# Loop through the array twice to handle circularity
for i in range(2 * n):
current_num = nums[i % n]
# While stack is not empty and the number at the index on top of the stack
# is smaller than the current number
while stack and nums[stack[-1]] < current_num:
# The current number is the next greater element for the index on top of the stack
result[stack.pop()] = current_num
# Push the current index (modulo n) onto the stack
stack.append(i % n)
return result
Next Greater Element II in Java
class Solution {
public int[] nextGreaterElements(int[] nums) {
int n = nums.length;
int[] result = new int[n];
Arrays.fill(result, -1); // Initialize result array with -1
// Use a Deque as a stack to store indices. Deque is preferred over Stack in modern Java.
Deque<Integer> stack = new ArrayDeque<>();
// Loop through the array twice to handle circularity
for (int i = 0; i < 2 * n; i++) {
int currentNum = nums[i % n];
// While stack is not empty and the number at the index on top of the stack
// is smaller than the current number
while (!stack.isEmpty() && nums[stack.peek()] < currentNum) {
// The current number is the next greater element for the index on top of the stack
result[stack.pop()] = currentNum;
}
// Push the current index (modulo n) onto the stack
stack.push(i % n);
}
return result;
}
}
Next Greater Element II in C++
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
int n = nums.size();
vector<int> result(n, -1); // Initialize result vector with -1
stack<int> s; // Stack to store indices
// Loop through the array twice to handle circularity
for (int i = 0; i < 2 * n; ++i) {
int current_num = nums[i % n];
// While stack is not empty and the number at the index on top of the stack
// is smaller than the current number
while (!s.empty() && nums[s.top()] < current_num) {
// The current number is the next greater element for the index on top of the stack
result[s.top()] = current_num;
s.pop();
}
// Push the current index (modulo n) onto the stack
// We push i % n instead of just i to handle the conceptual doubled array correctly.
// This simpler version works because the NGE for an element in the circular array is
// the same as its NGE in the doubled array, which this algorithm finds.
s.push(i % n);
}
return result;
}
};
Next Greater Element II in TypeScript
function nextGreaterElements(nums: number[]): number[] {
const n = nums.length;
const result: number[] = new Array(n).fill(-1); // Initialize result array with -1
const stack: number[] = []; // Stack to store indices
// Loop through the array twice to handle circularity
for (let i = 0; i < 2 * n; i++) {
const currentNum = nums[i % n];
// While stack is not empty and the number at the index on top of the stack
// is smaller than the current number
while (stack.length > 0 && nums[stack[stack.length - 1]] < currentNum) {
// The current number is the next greater element for the index on top of the stack
const idx = stack.pop()!;
result[idx] = currentNum;
}
// Push the current index (modulo n) onto the stack
stack.push(i % n);
}
return result;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.