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, return the next greater number for every element. Circular means that the element after the last one is the first one again. The next greater number of an element is the first number bigger than it that you meet walking forward from it, wrapping around to the start if needed. If there is no such number, the answer for that element is -1.

Example 1
Input: nums = [1, 2, 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
Input: nums = [1, 2, 3, 4, 3]
Output: [2, 3, 4, -1, 4]
Solution

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], the output of Example 2.

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.

The array 1, 2, 3, 4, 3 followed by a second copy of itself. In the first lap, 1, 2 and 3 each find a bigger number right next to them. The last 3 finds nothing in the first lap, so it wraps around into the second lap and reaches the 4 at index 3.

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]. The 2 answers the waiting 1, the first 3 answers the 2, and the 4 answers that 3. The last 3 is smaller than the 4, so it simply joins the list. After the first lap, the 4 and the last 3 are still waiting. In the second lap the 1, 2 and 3 answer nobody, then the 4 arrives and answers the 3. Nothing ever answers the 4, so it keeps -1.

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 introduction to monotonic stacks shows the same idea on an array that does not wrap around.

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], every search goes all the way round and finds nothing. That is about n steps for each of the n numbers, roughly n² in all: 100 million steps for 10,000 numbers. The stack needs only the two laps, plus at most one removal for each number.

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] both fives keep waiting.

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 k runs from 0 to 2n - 1, and the real index is k % n, the remainder after dividing by n. For n = 5, k = 5 gives index 0 again, and k = 8 gives index 3, the 4 in the picture.

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] never meets the 4, and the result comes out as [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 works in these steps:

  1. First, store the length of nums in n and create the result array answer. Fill it with -1 using Arrays.fill, so a number that is never answered already holds -1.
  2. Create stack, an ArrayDeque of the indices still waiting. ArrayDeque is Java's array-based double-ended queue; its push, peek and pop all work on one end, which serves as the top of the stack.
  3. Walk around the array twice with one loop: k runs from 0 to 2 * n - 1, and i = k % n is the real index for that step.
  4. Inside, a while loop looks at the index on top of the stack. As long as its number is smaller than nums[i], it pops that index and writes nums[i] into answer at that index.
  5. Then, only in the first lap (k < n), push i so it waits for its own bigger number.
  6. When the loop is done, return answer.

The main method runs both examples, an array that only goes down, two equal numbers, a single number and an empty array.

Java
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:

Output
[2, -1, 2]
[2, 3, 4, -1, 4]
[-1, 3, 3]
[-1, -1]
[-1]
[]

Look at the second line, [2, 3, 4, -1, 4]. The last 4 in it is the answer for the last 3, found in the second lap, just as in the picture.

In the third line, from [3, 2, 1], nothing is answered in the first lap, so all three indices wait on the stack. In the second lap the 3 at index 0 arrives and answers both the 1 and the 2, giving [-1, 3, 3]; the 3 itself is the biggest and keeps -1.

[5, 5] gives [-1, -1] because neither five is strictly bigger than the other. A single number has nothing to compare with and gets -1, and the empty array gives [], because with n = 0 the loop never runs.

Complexity

The work is the two laps, plus the pops inside the while loop.

  • 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 [3, 2, 1]. The answer array is the output.

The version without wrap-around, where the answers are looked up for the numbers of a second array, is Next Greater Element I.