LeetCode 503: Next Greater Element II Solution

Master LeetCode problem 503 (Next Greater Element II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

503. Next Greater Element II

Problem Explanation

Explanation

To solve this problem, we can use a stack to keep track of indices of elements for which we have not found the next greater element yet. We iterate through the given circular array twice to cover the circular property. In each iteration, we update the result array with the next greater element for the elements at the top of the stack. If the current element is greater than the element at the top of the stack, we update the result array and pop the stack. We continue this process until the stack is empty or the current element is not greater than the element at the top of the stack.

Solution Code

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        int n = nums.length;
        int[] result = new int[n];
        Arrays.fill(result, -1);
        Stack<Integer> stack = new Stack<>();
        
        for (int i = 0; i < 2 * n; i++) {
            int num = nums[i % n];
            while (!stack.isEmpty() && nums[stack.peek()] < num) {
                result[stack.pop()] = num;
            }
            if (i < n) {
                stack.push(i);
            }
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 503 (Next Greater Element II)?

This page provides optimized solutions for LeetCode problem 503 (Next Greater Element II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 503 (Next Greater Element II)?

The time complexity for LeetCode 503 (Next Greater Element II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 503 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 503 in Java, C++, or Python.

Back to LeetCode Solutions