Next Greater Element solution explained

Next Greater Element asks, for each value you are given, which value first appears to its right in a reference list and is strictly larger, or -1 if none does. Scan the reference list once with a stack that holds values still waiting for an answer, kept in decreasing order: each new value pops and answers every smaller value on top, then waits itself. Store the answers in a map and the queries become lookups, for O(n + q) time overall.

By Published 8 min read

The task, restated

You receive two lists. The first, call it the reference list, holds distinct integers. The second, the queries, holds some of those same integers. For every query, find where it sits in the reference list, look to its right, and report the first value that is strictly bigger. If nothing to its right is bigger, report -1. Return one answer per query, in the order the queries were given.

reference = [5, 2, 8, 6, 3, 9]
queries   = [2, 6, 9]

2 -> look right: 8 is the first bigger value   -> 8
6 -> look right: 3 is smaller, 9 is bigger      -> 9
9 -> nothing to its right                       -> -1

answer = [8, 9, -1]
A reference list and three queries made up for this page

Some versions of the problem skip the second list and ask for the next greater value of every position, and a well-known sibling treats the list as a circle so the search wraps around to the front. Ask which one you have. Also confirm that the values really are distinct, because the two-list version relies on finding each query's position by value.

Why it shows up in interviews

It is the cleanest introduction to the monotonic stack, a tool that reappears in temperature-wait problems, stock spans, histogram areas and digit-removal puzzles. The brute force is obvious, so the conversation quickly turns to whether you can spot the wasted work and name a structure that removes it. Interviewers also listen for a correct amortized argument, because the nested loop in the fast solution looks quadratic to anyone who counts loops instead of operations.

The direct approach

For each query, find its index in the reference list, then walk right until a bigger value appears. With a map from value to index the first step is O(1), but the walk is still up to n steps, so the total is O(n · q). On a list that falls steadily, such as 9, 8, 7, 6 and so on, every walk runs to the end. The code is short and makes a reliable checker for the fast version.

def next_greater_slow(values):
    answer = []
    for i, v in enumerate(values):
        found = -1
        for w in values[i + 1:]:
            if w > v:
                found = w
                break
        answer.append(found)
    return answer
Python: scan to the right for every position. O(n²) for all positions, used as a test reference.

Spotting the wasted work

Look at the reference list from left to right. When 2 arrives after 5, neither has an answer yet, and 2 sits below 5 in value. When 8 arrives, it answers both of them at once: 2 gets 8, and 5 gets 8. The values that are still waiting always form a decreasing sequence, because any waiting value that was smaller than a later arrival would have been answered by it. That decreasing sequence is a stack. A new value pops everything smaller from the top, recording itself as their answer, and then joins the stack to wait for its own answer. Whatever is still on the stack at the end has no bigger value to its right and gets -1.

def next_greater_each(values):
    answer = [-1] * len(values)
    waiting = []                      # indexes, values decreasing from bottom to top
    for i, v in enumerate(values):
        while waiting and values[waiting[-1]] < v:
            answer[waiting.pop()] = v
        waiting.append(i)
    return answer


def next_greater_element(queries, reference):
    nxt = dict(zip(reference, next_greater_each(reference)))
    return [nxt[q] for q in queries]
Python: answer every position with a stack of indexes, then serve the queries from a map

Keeping indexes on the stack rather than values costs nothing and makes the helper correct for lists with repeated values too: equal values do not answer each other, because the comparison is strictly less than. The map in the second function is the only place that needs distinct values, which the two-list version promises.

function nextGreaterElement(queries, reference) {
  const answerOf = new Map();
  const waiting = []; // values, decreasing from bottom to top
  for (const v of reference) {
    while (waiting.length && waiting[waiting.length - 1] < v) {
      answerOf.set(waiting.pop(), v);
    }
    waiting.push(v);
  }
  return queries.map((q) => (answerOf.has(q) ? answerOf.get(q) : -1));
}
JavaScript: the same stack, storing values in a Map as they are answered

This version pushes values straight onto the stack, which is fine here because the values are distinct. Anything never written into the map was still waiting at the end, so the lookup falls back to -1.

Complexity

n values in the reference list, q queries
ApproachTimeExtra space
Scan right from each queryO(n · q)O(1), or O(n) with an index map
Monotonic stack plus a mapO(n + q)O(n) for the stack and the map
Circular variant, two lapsO(n)O(n)
n values in the reference list, q queries. Scroll sideways on a small screen.

The circular variant

In the wrap-around version there is a single list, and after the last position the search continues from the front. For [4, 1, 3, 4, 2] the answers are -1, 3, 4, -1 and 4: the final 2 wraps to the front and finds 4, while both 4s find nothing strictly bigger anywhere. The trick is to run the same stack over the list twice. During the first lap, push every index. During the second lap, only pop and answer; do not push again, or positions would wait for themselves.

def next_greater_circular(values):
    n = len(values)
    answer = [-1] * n
    waiting = []
    for step in range(2 * n):
        v = values[step % n]
        while waiting and values[waiting[-1]] < v:
            answer[waiting.pop()] = v
        if step < n:
            waiting.append(step)
    return answer
Python: circular next greater value, two laps over the indexes

Other twists on the same stack

  • Distance instead of value: store how many steps away the bigger value is. This is the shape of the well-known daily temperatures problem.
  • Next smaller value: flip the comparison so the stack increases from bottom to top.
  • Previous greater value: scan from right to left, or read the answer from the stack top before pushing.
  • Greater or equal counts: change the strict comparison and check what happens with repeated values.
  • Next greater by digit rearrangement (the next permutation of a number) is a different problem with a similar name; it is solved with a right-to-left scan and a swap, not a stack.

Edge cases

  • An empty query list returns an empty list.
  • A reference list with one value: its answer is -1.
  • A strictly falling list: every answer is -1 and the stack never pops until the end.
  • A strictly rising list: every value is answered by its right neighbor.
  • The largest value: always -1 in the non-circular version.

Frequent slips

  • Popping while the top is less than or equal, which makes a repeated value count as greater.
  • Answering the queries in reference-list order instead of query order.
  • Pushing during the second lap of the circular version, so a value can end up as its own answer.
  • Calling the solution O(n²) because of the nested loop, or claiming O(n) without the push-once, pop-once argument.
  • Forgetting that values left on the stack need -1, which a prefilled answer list handles for free.

Saying it out loud

Fictional example

Moving from the brute force to the stack
Candidate
The simple version scans right from each query, which is n times q in the worst case, for example on a falling list.
Candidate
The waste is that a single big value answers many earlier values at once. The values still waiting are always in decreasing order, so I can keep them on a stack.
Candidate
Each new value pops every smaller value off the top and becomes their answer, then waits on the stack itself. I record answers in a map, then look up each query.
Interviewer
What if the list could contain repeats?
Candidate
I would store indexes on the stack and answer per position. The map from value to answer only works because the values are distinct.

Online Stock Span runs this stack in the opposite direction, looking back for the previous larger price as prices stream in. Asteroid Collision uses the same pop-while-beaten loop with a three-way outcome, and Remove K Digits turns it into a greedy rule. If you have not used a stack for bracket matching yet, start with Valid Parentheses.

Using Natively in your practice

The hard part of this problem is not the code but saying why the stack stays in decreasing order. Natively runs on Mac and Windows; during a mock round it can read the two lists from a screenshot, suggest the monotonic stack when you are stuck on the brute force, and transcribe your explanation so you can check afterwards whether the amortized argument came out clearly. The AI coding interview helper page covers the rest.

Questions people ask

How do you solve Next Greater Element?

Scan the reference list once with a stack of values still waiting for an answer. Each new value pops every smaller value off the top and becomes their answer, then is pushed. Save answers in a map, give -1 to anything left on the stack, and look up each query.

What is a monotonic stack?

A stack whose contents stay sorted, here decreasing from bottom to top. Keeping that order means a new value can resolve every smaller waiting value by popping from the top until the order holds again.

What is the time complexity of Next Greater Element with a stack?

O(n + q) for n reference values and q queries. Every value is pushed once and popped at most once, and each query is a map lookup.

How do you handle the circular version of Next Greater Element?

Walk the indexes twice. Push indexes only during the first lap and keep popping and answering during the second, so values near the end can find a bigger value near the front.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP