Next Greater Element II
For each number in a circular array, find the first bigger number ahead of it, wrapping around to the start.
Given a circular array of integers nums
Example 1
Output: [2, -1, 2]
Explanation: for the last 1, walking forward wraps around to the start and reaches the 2 at index 1.
Example 2
Output: [2, 3, 4, -1, 4]
The Idea
Picture the numbers of Example 2, 1, 2, 3, 4 and 3, written around a clock face. Each number looks clockwise, past its neighbours, for the first number bigger than itself. For the 1 that is the very next number, 2. The same goes for the 2, which finds 3, and the first 3, which finds 4.
The 4 looks all the way round and finds nothing bigger, so its answer is -1. The last 3 has nothing after it in the array, but on the clock face its next neighbour is the 1 at the start. It passes the 1, the 2 and the 3 and stops at the 4. Together that gives [2, 3, 4, -1, 4]
Code cannot walk a clock face, but it can walk the array twice. Look at the picture below, where the array is written out a second time after itself.
In the first lap, the short arrows labelled "the next number is bigger" show the 1, 2 and 3 each finding a bigger number right next to them. The 3 at index 4 finds nothing in the first lap, so its search runs on into the second lap, which is the start of the array again. The long arrow, "the last 3 wraps around to the 4", stops at the 4 at index 3. The second lap holds all the other numbers of the array, so any search that starts in the first lap ends inside it.
Searching forward from every number on its own can take up to n steps each, for an array of n numbers. Can one walk answer them all? Turn the search round: instead of each number looking ahead, let numbers wait. Walk the array. When a new number arrives, it is the answer for every waiting number smaller than itself, and then it joins the list of numbers still waiting for a bigger one.
Which of the waiting numbers are smaller? On the list, a newer waiting number is never bigger than an older one, because a bigger one would have answered the older one when it arrived. So the newest waiting number is the smallest. The new number checks the newest one first, answers it and removes it, and repeats until a waiting number is not smaller.
Follow it on [1, 2, 3, 4, 3]
A list where you only add to and take from the end, the top, is called a stack. Here its values never increase from bottom to top, and a stack kept in order like that is called a monotonic stack, monotonic meaning that it always moves one way. The
Solution Approach
First comes why a separate search from each number is slow. Then three things need settling: what the stack holds, how to walk the circle twice without copying the array, and what unanswered numbers get.
Searching from each number
What does the simple way cost? For each index, step forward one position at a time, wrapping at the end, until a bigger number turns up or the search is back where it started. When all the numbers are equal, as in [5, 5, 5, 5]
What the stack holds
Should the stack keep the waiting numbers or their positions? Their positions, the indices. When a number is answered, the answer goes into the result at that number's own index, and its value can always be read back as nums[index]
A waiting number is removed only when the new number is strictly bigger. Equal numbers do not answer each other, so in [5, 5]
Going around twice
Why two laps, and how do we get them without a copy? Any number in the first lap meets every other number within its next n - 1 steps, and those all fit in the second lap. So a counter kk % nkk
The second lap is only there to answer numbers still waiting, so it adds nothing to the stack: each index waits once, from the first lap. The second lap is also what the circle needs. With a single lap, as for an array that does not wrap, the last 3 of [1, 2, 3, 4, 3][2, 3, 4, -1, -1]
Numbers that are never answered
What about the 4 in Example 2, which no number ever answers? Filling the result with -1 before the walk covers it. A number that is answered gets its -1 replaced, and the biggest number, along with any copies of it, keeps -1.
Java Solution
The method nextGreaterElements
- First, store the length of
innums and create the result arrayn . Fill it with -1 usinganswer , so a number that is never answered already holds -1.Arrays.fill - Create
, anstack of the indices still waiting.ArrayDeque is Java's array-based double-ended queue; itsArrayDeque ,push andpeek all work on one end, which serves as the top of the stack.pop - Walk around the array twice with one loop:
runs from 0 tok , and2 * n - 1 is the real index for that step.i = k % n - Inside, a
loop looks at the index on top of the stack. As long as its number is smaller thanwhile , it pops that index and writesnums[i] intonums[i] at that index.answer - Then, only in the first lap (
), pushk < n so it waits for its own bigger number.i - When the loop is done, return
.answer
The main
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
public class NextGreaterElementII {
public static int[] nextGreaterElements(int[] nums) {
int n = nums.length;
int[] answer = new int[n];
Arrays.fill(answer, -1); // kept by anyone never answered
Deque<Integer> stack = new ArrayDeque<>(); // indices still waiting
for (int k = 0; k < 2 * n; k++) { // go around twice
int i = k % n; // the real index for step k
while (!stack.isEmpty() && nums[stack.peek()] < nums[i]) {
answer[stack.pop()] = nums[i]; // nums[i] answers a smaller waiter
}
if (k < n) {
stack.push(i); // each index waits only once
}
}
return answer;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(nextGreaterElements(new int[] {1, 2, 1})));
System.out.println(Arrays.toString(nextGreaterElements(new int[] {1, 2, 3, 4, 3})));
System.out.println(Arrays.toString(nextGreaterElements(new int[] {3, 2, 1})));
System.out.println(Arrays.toString(nextGreaterElements(new int[] {5, 5})));
System.out.println(Arrays.toString(nextGreaterElements(new int[] {7})));
System.out.println(Arrays.toString(nextGreaterElements(new int[] {})));
}
}
Running it prints:
[2, -1, 2]
[2, 3, 4, -1, 4]
[-1, 3, 3]
[-1, -1]
[-1]
[]
Look at the second line, [2, 3, 4, -1, 4]
In the third line, from [3, 2, 1][-1, 3, 3]
[5, 5][-1, -1][]
Complexity
The work is the two laps, plus the pops inside the while
- Time: O(n). The loop takes 2n steps. Each index is pushed once, in the first lap, and can be popped at most once, so the pops over both laps add up to at most n, however they are spread.
- Space: O(n) for the stack, which holds every index at the end of the first lap when the numbers only go down, as in
. The[3, 2, 1] array is the output.answer
The version without wrap-around, where the answers are looked up for the numbers of a second array, is