AlgoTales · Roadmap

Next greater element

Intermediate · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Next greater element asks, for every item in a list, what is the first bigger item to its right. A stack of "still waiting" items answers all of them in one pass, because a new bigger value settles every smaller waiting value at once.

Practical use cases

  • Web app: Weather page: days until a warmer day. A weather site shows, under each day's forecast, how many days until it gets warmer. Looking ahead from every day separately repeats a lot of work. With a waiting stack, each warmer day instantly answers all the cooler days waiting for it, and the whole month is computed in a single loop.
  • Web app: Stock alert: next day the price beats today. An investing app tells a user, for each day in their holding history, when the price next went above that day's price. The stack holds days with no answer yet. Every new price pops all the lower days, writing their answers on the way.
  • System: Parsers, trees and skyline views. Compilers, layout engines and chart tools often need to know the nearest larger neighbour of an item, for example which taller building blocks the view. The stack method answers this for every item with one sweep, which keeps rendering and parsing fast even for very large inputs.

The story: Who Beats My Score?

The school cricket team's scorebook listed the runs of each batsman in batting order: 4, 5, 2, 10, 8. Kabir, who scored 4, grumbled, "I wonder who is the next person after me who scored more than I did?" Mira loved such puzzles and set out to answer it for every player.

Her first idea was slow: for each batsman, walk right until you find a bigger score. For long lists, that is an endless amount of re-walking. Then she remembered the monotonic stack and made a waiting room: every player who has not yet found a bigger score waits there, with the latest arrival on top.

Now she read the scores once. When a new score arrived, she checked the waiting room from the top. Anyone waiting with a smaller score had just found their answer: the newcomer! Mira wrote it down and sent them away. Then the newcomer joined the waiting room.

At the end, those still in the waiting room had nobody bigger after them, so their answer was -1. In one pass, with every player entering and leaving the room at most once, all the answers were ready. That is the next greater element pattern.

How to spot this problem, and where you need it

For each entry in a series you need to know when or where something bigger next appears, and looking ahead separately from every entry is slow for long series.

Signs you need it

  • The problem says "next greater", "next warmer day", "next higher price", "first taller building to the right" or "days to wait".
  • You loop forward from each position until you find a bigger value, and this nested loop gets very slow on large inputs.
  • You are producing one answer per element, and many elements share the same answer.

Where to use it in a project

  • Temperature, price and traffic timelines that show how long until a higher value.
  • Alert features, such as "notify when the price beats today's price", in finance or shopping apps.
  • Layout and charting code that needs the nearest larger neighbour of each item.

The solution

Move through the list from left to right with a stack holding positions that have not yet found a bigger value. For each new value, while the top waiting position has a smaller value, pop it and record the new value as its answer. Then push the new position. Anything still on the stack at the end has no bigger value after it.

Payoff: Before: scanning ahead from each of 50,000 days, millions of comparisons. After: each day is pushed and popped once, about 100,000 steps.

Explain it like I am 8

Everyone in the line holds a card with a number. Each person looks to the right for the first person with a bigger number. Instead of everyone looking, we keep a "still looking" group. Each new person says "Anyone smaller than me? I'm your answer!" and those people leave the group.

How it works, step by step

  1. Make an empty stack of positions (indexes) of items that have not found their answer yet, and an answer list filled with -1.
  2. Walk left to right. For each item x, while the stack is not empty and the item at the top position is smaller than x, pop that position and set its answer to x.
  3. Push the current position. It now waits for something bigger.
  4. Positions left on the stack at the end keep their -1: nothing bigger came after them.
  5. Why indexes? The answer list is filled by position, so the stack must remember where each waiting item sits.

The code in four languages

PHP

<?php
// For each number, find the next number to its right that is bigger (or -1).
function nextGreater(array $nums): array {
    $n = count($nums);
    $answer = array_fill(0, $n, -1);
    $stack = [];                                     // indexes still waiting

    for ($i = 0; $i < $n; $i++) {
        // the newcomer is the answer for every smaller number waiting
        while ($stack && $nums[end($stack)] < $nums[$i]) {
            $answer[array_pop($stack)] = $nums[$i];
        }
        $stack[] = $i;                               // now it waits for someone bigger
    }
    return $answer;                                  // leftovers keep -1
}

echo implode(', ', nextGreater([4, 5, 2, 10, 8])) . PHP_EOL;   // 5, 10, 10, -1, -1

JavaScript

// For each number, find the next number to its right that is bigger (or -1).
function nextGreater(nums) {
  const n = nums.length;
  const answer = new Array(n).fill(-1);
  const stack = [];                                  // indexes still waiting

  for (let i = 0; i < n; i++) {
    // the newcomer is the answer for every smaller number waiting
    while (stack.length && nums[stack[stack.length - 1]] < nums[i]) {
      answer[stack.pop()] = nums[i];
    }
    stack.push(i);                                   // now it waits for someone bigger
  }
  return answer;                                     // leftovers keep -1
}

console.log(nextGreater([4, 5, 2, 10, 8]).join(', '));   // 5, 10, 10, -1, -1

Java

import java.util.*;

public class Main {
    // For each number, find the next number to its right that is bigger (or -1).
    static int[] nextGreater(int[] nums) {
        int n = nums.length;
        int[] answer = new int[n];
        Arrays.fill(answer, -1);
        Deque<Integer> stack = new ArrayDeque<>();       // indexes still waiting

        for (int i = 0; i < n; i++) {
            // the newcomer is the answer for every smaller number waiting
            while (!stack.isEmpty() && nums[stack.peek()] < nums[i]) {
                answer[stack.pop()] = nums[i];
            }
            stack.push(i);                               // now it waits for someone bigger
        }
        return answer;                                   // leftovers keep -1
    }

    public static void main(String[] args) {
        int[] result = nextGreater(new int[]{4, 5, 2, 10, 8});
        System.out.println(Arrays.toString(result));     // [5, 10, 10, -1, -1]
    }
}

Go

package main

import "fmt"

// nextGreater finds, for each number, the next number to its right that is bigger (or -1).
func nextGreater(nums []int) []int {
	n := len(nums)
	answer := make([]int, n)
	for i := range answer {
		answer[i] = -1
	}
	var stack []int // indexes still waiting

	for i := 0; i < n; i++ {
		// the newcomer is the answer for every smaller number waiting
		for len(stack) > 0 && nums[stack[len(stack)-1]] < nums[i] {
			answer[stack[len(stack)-1]] = nums[i]
			stack = stack[:len(stack)-1]
		}
		stack = append(stack, i) // now it waits for someone bigger
	}
	return answer // leftovers keep -1
}

func main() {
	fmt.Println(nextGreater([]int{4, 5, 2, 10, 8})) // [5 10 10 -1 -1]
}

Time: O(n) · Extra space: O(n). Every index is pushed once and popped at most once. The brute-force way (searching right from each item) can take O(n²).

Watch out for

  • Using <= instead of <: equal values are not "greater", so they must keep waiting.
  • Forgetting that positions left on the stack at the end keep -1. Fill the answer list with -1 at the start.
  • Pushing the value instead of the index, so you can no longer tell where to store the answer.

Quick check

  1. What is the next greater element for each of [4, 5, 2, 10, 8]?
    • [5, 10, 10, -1, -1]
    • [5, 10, 5, -1, 10]
    • [10, 10, 10, 10, -1]
  2. What does the stack hold while walking?
    • Items that already found an answer
    • Indexes of items still waiting for a bigger one
    • The biggest item so far
  3. What is the time complexity of this stack method?
    • O(n²)
    • O(n log n)
    • O(n)