medium Next Greater Element II
Problem Statement
Given a circular integer array nums, return the array containing the next greater number for each element in nums.
A next greater number of a number num is the first greater number than the current number in its traversing-order in the array, which means you could search circularly to find its next greater number. If the next greater element doesn't exist, return -1 for the particular number number.
Examples
-
Example 1:
- Input: nums =
[2, 1, 2, 4, 3] - Expected Output:
[4, 2, 4, -1, 4] - Justification: For
2, the next greater number is4. For1, it's2(the next number in the array). For the second2,4is again the next greater. For4, there's no greater number, hence-1. For3, looping over,4is the next greater number.
- Input: nums =
-
Example 2:
- Input: nums =
[1, 5, 3, 6, 4] - Expected Output:
[5, 6, 6, -1, 5] - Justification: The next greater for
1is5, for5is6, for3is6again, and for6there's no greater number (-1). For4, considering the circular nature,5is the next greater number.
- Input: nums =
-
Example 3:
- Input: nums =
[9, 8, 7, 3, 2, 1, 6] - Expected Output:
[-1, 9, 9, 6, 6, 6, 9] - Justification: For
9, as it's the greatest, no number is greater, so-1. For8and7,9is the next greater number. For3,2, and1, the next greater number is6, considering the circular array. For6,9is the next greater number by looping over.
- Input: nums =
Try it yourself
Try solving this question here:
✅ Solution Next Greater Element II
Problem Statement
Given a circular integer array nums, return the array containing the next greater number for each element in nums.
A next greater number of a number num is the first greater number than the current number in its traversing-order in the array, which means you could search circularly to find its next greater number. If the next greater element doesn't exist, return -1 for the particular number number.
Examples
-
Example 1:
- Input: nums =
[2, 1, 2, 4, 3] - Expected Output:
[4, 2, 4, -1, 4] - Justification: For
2, the next greater number is4. For1, it's2(the next number in the array). For the second2,4is again the next greater. For4, there's no greater number, hence-1. For3, looping over,4is the next greater number.
- Input: nums =
-
Example 2:
- Input: nums =
[1, 5, 3, 6, 4] - Expected Output:
[5, 6, 6, -1, 5] - Justification: The next greater for
1is5, for5is6, for3is6again, and for6there's no greater number (-1). For4, considering the circular nature,5is the next greater number.
- Input: nums =
-
Example 3:
- Input: nums =
[9, 8, 7, 3, 2, 1, 6] - Expected Output:
[-1, 9, 9, 6, 6, 6, 9] - Justification: For
9, as it's the greatest, no number is greater, so-1. For8and7,9is the next greater number. For3,2, and1, the next greater number is6, considering the circular array. For6,9is the next greater number by looping over.
- Input: nums =
Solution
To solve this problem, we'll employ a stack to keep track of the indices of elements for which we're trying to find the next greater number. We loop through the array twice to simulate the circular nature of the problem. This ensures that for every element, we get a chance to check the rest of the array and then loop back to check the elements before it, if necessary.
Our approach works because, with the stack, we maintain elements in decreasing order from top to bottom. This way, when we encounter an element greater than the stack's top, we know we've found the next greater element for the indices stored in the stack. By looping twice, we ensure every element is considered in its circular context, making the approach effective for finding the next greater element in a circular array.
Step-by-Step Algorithm
- Initialize an empty stack to keep track of indices whose next greater element hasn't been found yet.
- Create an array
resultwith the same length as the input arraynums, filled with-1. This array will store the next greater element for each position innums. - Loop through the array twice (to account for the circular nature of the problem) using an index variable
ithat goes from0to2 * len(nums) - 1. The actual index for accessing elements innumswill bei % len(nums)due to the circular nature. - In each iteration of the loop, do the following:
- Use the current index
i % len(nums)to access the element innums. - While the stack is not empty and the current element is greater than the element at the index at the top of the stack:
- Pop the index from the top of the stack.
- Update the
resultarray at the popped index with the current element, indicating the next greater element has been found.
- If the loop is in its first iteration through
nums(i.e.,i < len(nums)), push the current indexi % len(nums)onto the stack.
- Use the current index
- After completing the loop, return the
resultarray, which now contains the next greater element for each position in the input arraynums.
Algorithm Walkthrough
Let's consider the input [9, 8, 7, 3, 2, 1, 6].
- Initial State:
nums = [9, 8, 7, 3, 2, 1, 6]result = [-1, -1, -1, -1, -1, -1, -1](Assuming no greater element found yet)stack = [](Empty)
First Pass:
- Step 1: Index
0, Element9- Add
0to the stack.stack = [0] result = [-1, -1, -1, -1, -1, -1, -1]
- Add
- Step 2: Index
1, Element8- Add
1to the stack.stack = [0, 1] result = [-1, -1, -1, -1, -1, -1, -1]
- Add
- Step 3: Index
2, Element7- Add
2to the stack.stack = [0, 1, 2] result = [-1, -1, -1, -1, -1, -1, -1]
- Add
- Step 4: Index
3, Element3- Add
3to the stack.stack = [0, 1, 2, 3] result = [-1, -1, -1, -1, -1, -1, -1]
- Add
- Step 5: Index
4, Element2- Add
4to the stack.stack = [0, 1, 2, 3, 4] result = [-1, -1, -1, -1, -1, -1, -1]
- Add
- Step 6: Index
5, Element1- Add
5to the stack.stack = [0, 1, 2, 3, 4, 5] result = [-1, -1, -1, -1, -1, -1, -1]
- Add
- Step 7: Index
6, Element6- Since
6is greater than1,2, and3. Update their positions inresult. - Pop
5,4, and3fromstack, and updateresultfor these indices. stack = [0, 1, 2, 6]result = [-1, -1, -1, 6, 6, 6, -1]
- Since
- Step 8: Index
i % 7 = 7 % 7 = 0, Element9- Since
9is greater than6,8, and7. Update their positions inresult. - Pop
6,2, and1fromstack, and updateresultfor these indices. stack = [0]result = [-1, 9, 9, 6, 6, 6, 9]
- Since
- Continue iterating the array in the second pass.
Final State:
result = [-1, 9, 9, 6, 6, 6, -1]
Code
public class Solution {
// Function to find the next greater element for each element in the circular array
public int[] nextGreaterElements(int[] nums) {
int n = nums.length;
int[] result = new int[n]; // Result array
java.util.Stack<Integer> stack = new java.util.Stack<>(); // Stack to keep track of indices
java.util.Arrays.fill(result, -1); // Initialize result array with -1
for (int i = 0; i < n * 2; i++) {
int num = nums[i % n]; // Current number (use modulo for circular array)
// Find next greater element
while (!stack.isEmpty() && nums[stack.peek()] < num) {
result[stack.pop()] = num; // Update result for the index popped from the stack
}
if (i < n) stack.push(i); // Push current index to stack
}
return result; // Return the result array
}
// Main method to test the solution
public static void main(String[] args) {
Solution solution = new Solution();
// Test cases
int[] example1 = { 2, 1, 2, 4, 3 };
int[] example2 = { 1, 5, 3, 6, 4 };
int[] example3 = { 9, 8, 7, 3, 2, 1, 6 };
// Print results
System.out.println(
java.util.Arrays.toString(solution.nextGreaterElements(example1))
);
System.out.println(
java.util.Arrays.toString(solution.nextGreaterElements(example2))
);
System.out.println(
java.util.Arrays.toString(solution.nextGreaterElements(example3))
);
}
}
Complexity Analysis
- Time Complexity:
, where n is the number of elements in the array. Each element is processed at most twice - once when added to the stack and once when removed. - Space Complexity:
for the stack and the result array. The stack can grow up to the size of the input array in the worst case.
🤖 Don't fully get this? Learn it with Claude
Stuck on Next Greater Element II? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Next Greater Element II** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Next Greater Element II** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Next Greater Element II**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Next Greater Element II**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.