Scrivio Interview library
Stacks and queuesStacks, queues and heapsReported 20 times · 15 min read · updated 14 November 2026

For every element of an array, find the next greater element to its right.

1What the question asks, told as a row of people

Picture a row of people standing one behind another for a photograph, all facing to the right. Each person is a different height, and each one wants to know who is the first person in front of them, to their right, who is taller than they are. A short person near the left may only need to look one place ahead. A tall person may have to look past many shorter heads before someone taller appears, and the tallest person of all never finds anyone.

The question is that same picture with numbers. The array holds the heights, and for every element we must report the first value to its right that is strictly greater, meaning bigger and not equal. If no such value exists, we report -1. The answers form a new array of the same length.

Let us use [2, 7, 3, 5, 4, 6, 8] and work it by hand. For 2 the next value, 7, is already greater, so its answer is 7. For 7 we look at 3, 5, 4 and 6, all smaller, and reach 8, so its answer is 8. For 3 it is 5, for 5 it is 6, because 4 is smaller, and for 4 and for 6 the answers are 6 and 8. The last element, 8, has nothing to its right, so its answer is -1. The result is [7, 8, 5, 6, 6, 8, -1].

PictureThe example and the answer for each element

Top row: the array. Bottom row: for each element, the first strictly greater value to its right, or -1 when there is none.

  1. 2735468785668-1

    1Under each value is its answer. 7 skips over 3, 5, 4 and 6 to reach 8, and 8 itself has nothing to its right, so it gets -1.

What to assume

Do we return values or positions?
Values here.
What about equal values?
Greater means strictly greater, so in [1, 1, 2] the first 1 skips the second and both get 2.
What if nothing is greater?
We write -1.
Does the search wrap round to the start?
Not in this version.
How long can the array be?
Perhaps 100,000 elements.

A careful candidate asks a few questions first. Do we return values or positions? Values here, and positions need only a small change, covered in the follow-ups. What about equal values? Greater means strictly greater, so in [1, 1, 2] the first 1 skips the second and both get 2. What if nothing is greater? We write -1. Does the search wrap round to the start? Not in this version. How long can the array be? Perhaps 100,000 elements, which matters for the cost, as we will see.

2How to recognise a nearest greater element problem

When we first read this question, the plan seems obvious: for each element, look to its right until something bigger turns up. That is exactly what we did by hand, and it is the brute force we will write next. A beginner rarely suspects that there is anything cleverer to find, because the question seems to ask for nothing more than a lot of looking.

Let us read the words slowly, one clue at a time. The first clue is the word next. We do not want the largest value to the right, only the nearest one that passes the test, so the order of the elements matters, and sorting, which forgets the order, is ruled out at once.

The second clue is the word greater. The answer for one element depends on comparing sizes, and in the row of people a tall person blocks the view of everyone shorter behind them. That means some elements can stop mattering for good once a taller one appears in front of them, and when elements stop mattering we can throw them away.

The third clue is for every element. We need many answers, one per position, and the nearest greater value of neighbouring elements is often the same, as 4 and 5 both get 6. Work that can be shared between answers is a strong hint that a single pass can produce them all.

These clues lead to the stacks and queues family, and to a technique called a monotonic stack. A stack is like a pile of plates: we may only put a plate on top, called a push, or take the top plate off, called a pop. Monotonic means always moving in one direction, so a monotonic stack keeps its values in order, here getting smaller from bottom to top. The rule to carry to new problems is that whenever each element needs the nearest bigger or smaller element on one side, a monotonic stack answers them all in one pass.

Some patterns look similar and do not fit. A heap, which always hands back the largest value it holds, gives the largest value to the right, not the nearest greater one. A sliding window, a frame of fixed width moved along the array, looks only at a few neighbours, while our answer may lie anywhere to the right.

3The honest first attempt, looking right from every element

The first solution anyone writes is the brute force, and it is a perfectly sensible start. For each position i we set the answer to -1, then look at each position j to the right of i. The first time a[j] is greater than a[i], we record a[j] and stop looking, which is what break does.

Java
static int[] nextGreaterSlow(int[] a) {
int[] result = new int[a.length];
for (int i = 0; i < a.length; i++) {
result[i] = -1; // until we find something greater
for (int j = i + 1; j < a.length; j++) { // look to the right of i
if (a[j] > a[i]) { result[i] = a[j]; break; } // the first greater value wins
}
}
return result;
}

Let us count its work on the example. From 2 we look at one value, 7, and stop. From 7 we look at five values, 3, 5, 4, 6 and 8. From 3 we look at one, from 5 at two, from 4 and from 6 at one each, and from 8 at none. That is 11 comparisons in all, which is fine for seven elements.

Now take an array that only gets smaller, such as [9, 8, 7, 6, 5, 4, 3, 2, 1]. Nobody ever finds a taller person, so every inner loop runs to the end. The first element looks at 8 values, the next at 7, and so on, which adds up to about n x n / 2 comparisons for n elements. We write that as O(n^2), read as order n squared. For 100,000 elements it is about five billion comparisons, far too slow. The extra space is O(1) apart from the result array.

So where is the waste? Look at what happens around 7. When we look right from 7, we pass 3, 5, 4 and 6, all shorter than 7. Now suppose the array had more elements to the left of 7, say a 10. Looking right from 10, we would pass 7 and then walk past 3, 5, 4 and 6 all over again, although none of them could ever be the answer for 10, because each is shorter than 7, which stands in front of them. The brute force keeps looking at people who are hidden behind someone taller.

4Getting to the stack, one observation at a time

Let us turn the waste into a rule. The first picture shows that from 7 we pass the shorter values 3, 5, 4 and 6 before finding 8. The second shows the more important fact. For any element standing to the left of 7, the view to the right stops at 7 or goes over its head, so 3, 5, 4 and 6 can never again be anyone's answer. They are hidden for good.

Step throughA tall value hides the smaller values behind it

Bars are the array values. Anyone standing to the left of 7 looks right and sees 7 first; 3, 5, 4 and 6 are hidden behind it.

  1. 2735468

    1Stand at 7 and look right. 3, 5, 4 and 6 are all shorter, so we pass them, and the first taller bar is 8.

  2. 2735468

    2Now stand at 2, left of 7. Its view stops at 7. For 2, or anything further left, 3, 5, 4 and 6 can never be the answer.

That suggests scanning from right to left. Why from the right? Because the answer for an element lies to its right, so if we walk from the right end, everything an element could need has already been seen when we reach it. As we walk, we keep a list of values still worth remembering, the ones not hidden behind something taller, and we keep that list as a stack, with the most recently seen value on top.

Now take one step. We arrive at a[i] and look at the top of the stack. If the top is less than or equal to a[i], it cannot be a[i]'s answer, and from now on it is hidden behind a[i] for every element further left. So we pop it and look at the new top, again and again. Once the top is greater than a[i], it is the nearest greater value to the right, and that is the answer. If the stack runs empty, nothing to the right is greater, and the answer is -1. Finally we push a[i], because it is now the nearest value that elements on its left will see.

Here a beginner usually asks a worried question. Is it safe to throw a popped value away forever? Let us check with 7 and the popped 6. Any element to the left of 7 that is smaller than 7 stops at 7 and never reaches 6. Any element larger than 7 is also larger than 6, so 6 cannot be its answer either. Either way, 6 is useless, and so is every value we pop.

Because we only ever pop values smaller than the newcomer and then push the newcomer on top, the stack always gets smaller from bottom to top, which is why it is called monotonic. The tempting mistake is to pop only values strictly smaller than a[i]. Then an equal value would stay on top and be reported as the answer, which breaks the rule that the answer must be strictly greater, so we pop on less than or equal.

One last worry is the cost. There is a while loop inside the for loop, so is this O(n^2) again? Count pushes and pops instead of loops. Each element is pushed exactly once and can be popped at most once, so all the while loops together run at most n times over the whole scan. A long run of pops, like the three popped by 7, is paid for by the cheap pushes that came before it. This way of counting the total instead of the worst single step is called amortised analysis, and it shows the whole scan is O(n).

5Watching the stack on the seven-element example

The picture plays the scan from right to left. The element being answered is marked under the pointer i. Cells marked as compared are values on the stack at that moment, the value that becomes the answer is marked as found, and greyed cells are values that were popped and are out of play. The panel lists the stack from bottom to top and the answers filled in so far, with _ for answers not yet known.

Watch the stack grow one value at a time while the answers come straight off the top, and then watch what happens when 7 arrives.

Step throughScanning 2, 7, 3, 5, 4, 6, 8 from the right with a stack

The stack holds the values still worth remembering, listed bottom to top. Marked cells are on the stack; greyed cells were popped.

  1. 20713253446586i
    stack
    empty
    result
    _ _ _ _ _ _ _

    1We start at the right end with an empty stack. Nothing has been answered yet, and i will move from index 6 down to index 0.

  2. 20713253446586i
    stack
    8
    answer
    -1
    result
    _ _ _ _ _ _ -1

    2i = 6, value 8. The stack is empty, so nothing to the right of 8 is greater, and its answer is -1. Then we push 8.

  3. 20713253446586i
    stack
    8 6
    answer
    8
    result
    _ _ _ _ _ 8 -1

    3i = 5, value 6. The top, 8, is greater than 6, so nothing is popped and the answer is 8. Then 6 goes on top of the stack.

  4. 20713253446586i
    stack
    8 6 4
    answer
    6
    result
    _ _ _ _ 6 8 -1

    4i = 4, value 4. The top, 6, is greater, so the answer is 6 at once. We push 4, and the stack reads 8 6 4 from bottom to top.

  5. 20713253446586i
    stack
    8 6 5
    popped
    4
    answer
    6
    result
    _ _ _ 6 6 8 -1

    5i = 3, value 5. The top, 4, is not greater than 5, so we pop it. Now the top is 6, which is greater, so the answer is 6. We push 5.

  6. 20713253446586i
    stack
    8 6 5 3
    answer
    5
    result
    _ _ 5 6 6 8 -1

    6i = 2, value 3. The top, 5, is greater than 3, so the answer is 5 and nothing is popped. We push 3, giving 8 6 5 3.

  7. 20713253446586i
    stack
    8
    popped
    3, 5, 6
    result
    _ _ 5 6 6 8 -1

    7i = 1, value 7. The top is 3, then 5, then 6, and none is greater than 7, so we pop all three. They sit behind 7 and are out of play.

  8. 20713253446586i
    stack
    8 7
    answer
    8
    result
    _ 8 5 6 6 8 -1

    8Now the top is 8, which is greater than 7, so the answer for 7 is 8. We push 7, and the stack is just 8 7.

  9. 20713253446586i
    stack
    8 7 2
    answer
    7
    result
    7 8 5 6 6 8 -1

    9i = 0, value 2. The top, 7, is greater than 2, so the answer is 7 with no popping. We push 2, though no element is left to use it.

  10. 20713253446586
    pushes
    7
    pops
    4
    result
    7 8 5 6 6 8 -1

    10The scan is over. Every element has its answer, [7, 8, 5, 6, 6, 8, -1], after seven pushes and only four pops.

Let us read the important frames back. In the frame for 8, the stack is empty, so the answer is -1 without any comparison. For 6 and 4 the top is already greater, so they each read their answer in one look and are pushed.

The frame for 5 shows the first pop. The top, 4, is not greater than 5, so it goes, and 6 becomes the top and the answer. Notice that 4 is popped exactly when a taller value arrives in front of it, as the row of people predicts.

The frames for 7 are the heart of the method. The stack holds 8 6 5 3, and 7 pops 3, then 5, then 6, because none is greater than 7. The top is then 8, which is the answer for 7, exactly the value our hand search found after passing four shorter values. Finally 2 finds 7 on top at once. Across the whole scan there were seven pushes and four pops, eleven stack moves for seven elements.

6The complete Java program

Here is the whole program. It uses ArrayDeque as the stack, which is the class Java recommends for stacks, faster than the older Stack class. main runs the example, a decreasing array where nothing has an answer, a pair of equal values, and the empty array, and each comment shows what the line prints.

Java
import java.util.*;
public class NextGreater {
// For each element, the first strictly greater element to its right, or -1.
static int[] nextGreater(int[] a) {
int[] result = new int[a.length];
Deque<Integer> stack = new ArrayDeque<>(); // candidates, decreasing from bottom to top
for (int i = a.length - 1; i >= 0; i--) { // scan from the right
while (!stack.isEmpty() && stack.peek() <= a[i]) {
stack.pop(); // hidden behind a[i]: never an answer again
}
result[i] = stack.isEmpty() ? -1 : stack.peek();
stack.push(a[i]); // a[i] is a candidate for elements to its left
}
return result;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(nextGreater(new int[] {2, 7, 3, 5, 4, 6, 8}))); // [7, 8, 5, 6, 6, 8, -1]
System.out.println(Arrays.toString(nextGreater(new int[] {5, 4, 3}))); // [-1, -1, -1]
System.out.println(Arrays.toString(nextGreater(new int[] {1, 1, 2}))); // [2, 2, -1]
System.out.println(Arrays.toString(nextGreater(new int[] {}))); // []
}
}

Let us read nextGreater in the order it runs. First we make the result array and an empty stack. The for loop starts i at the last index and counts down to 0, because we scan from the right.

Inside, the while loop does the popping. It checks that the stack is not empty before calling peek, which reads the top without removing it, because peek on an empty ArrayDeque returns null and comparing null with an int would throw an exception. While the top is less than or equal to a[i], we pop it.

When the while loop stops, either the stack is empty, and the answer is -1, or the top is greater than a[i], and the top is the answer. The conditional expression stack.isEmpty() ? -1 : stack.peek() says exactly that. Last, stack.push(a[i]) makes a[i] the new top, ready for the elements to its left.

In main, [5, 4, 3] gives [-1, -1, -1], because each value is pushed on top of a larger one and never finds a greater value. [1, 1, 2] gives [2, 2, -1], because the first 1 pops the equal 1 on top and finds 2 beneath it. The empty array never enters the loop and prints [].

7How much it costs, and the cases at the edges

Let us count on the example first. The scan made seven pushes and four pops, and each step read the top once. For n elements there are n pushes and at most n pops, about 3n simple steps, so the time is O(n). The brute force needed 11 comparisons here, which looks close, but on a decreasing array it needs about n x n / 2.

The stack can hold every element at once. That happens on a decreasing array, where nothing is ever popped. So the extra space is O(n), plus the result array that the question asks for.

Comparing the two approaches
ApproachTimeExtra spaceWork on the example
Look right from every elementO(n^2)O(1)11 comparisons
Monotonic stack, scanning from the rightO(n)O(n)7 pushes, 4 pops

The edge cases need no special code. An empty array skips the loop and returns an empty result. A single element finds an empty stack and gets -1. A decreasing array gives -1 everywhere. Equal values are popped by each other, so the answer stays strictly greater. Negative numbers need nothing special, since we only compare values.

If the question asked for greater or equal instead, the only change would be to pop on strictly less than, so that an equal value stays on top and becomes the answer. Being able to say which comparison you chose and why is a good sign in an interview.

8Follow-up questions

What if the array is circular, so the search wraps round to the start?

Then an element near the end may find its answer near the start. We run the same scan over twice the length, with i going from 2n - 1 down to 0, and read the array at i % n, so every element sees the whole array to its right, wrapping once. We only write answers while i is less than n. Each element is pushed at most twice, so it is still O(n) time and O(n) space.

How would you return positions or distances instead of values?

We push indexes onto the stack instead of values and compare a[stack.peek()] with a[i]. When the while loop stops, the top is the position of the next greater element, and the distance to it is that position minus i. This is exactly the daily temperatures problem, which asks how many days we wait for a warmer day.

Can you do it scanning from left to right?

Yes. The stack then holds the positions still waiting for their answer. When a[i] arrives, it pops every waiting position whose value is smaller than a[i] and writes a[i] as their answer, because a[i] is the first greater value they have met. Then it pushes i. Whatever is still waiting at the end gets -1. It costs the same O(n), and some people find it more natural because each element is answered the moment its taller neighbour appears.

9Conclusion

We found the next greater element for every position with a monotonic stack. Scanning from right to left, each element pops the values that are not greater than it, because they are hidden behind it for good, reads its answer from the top, and is pushed for the elements on its left. Each value is pushed once and popped at most once, so the cost is O(n) time and O(n) space, against O(n^2) for looking right from every element. The clue to remember is the nearest greater or smaller element on one side: that phrase means a monotonic stack.

What to say in the interviewAbout 70 seconds aloud

Open with

For every element I need the first strictly greater value to its right, or minus one, and I return values. The brute force looks right from each element until it finds a larger one, which is n squared on a decreasing array.

Then, if they want more

The waste is that we keep looking at values hidden behind a larger one; once a bigger value stands in front of them, they can never be the answer for anything further left. That is the nearest greater element pattern, so I use a monotonic stack.

I scan from right to left and keep a stack that decreases from bottom to top. For each element I pop everything less than or equal to it, since those are hidden from now on. The answer is the top, or minus one if the stack is empty, and then I push the element.

Each element is pushed once and popped at most once, so it is O(n) time and O(n) space. On the example, 7 pops 3, 5 and 6 and finds 8. For a circular array I would scan twice with i mod n.

About this answer

Last updated
14 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 20 times in that collection. How it is counted
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "For every element of an array, find the next greater element to its right.": https://scrivio-interview-library.netlify.app/data-structures/solutions/for-every-element-of-an-array-find-the-next-greater-element-to-i-d51aaf/