AlgoTales · Roadmap

Previous greater/smaller

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

Where you will meet this in real life

Previous greater or smaller finds, for each item, the nearest item on its left that is bigger or smaller. The stack keeps only the candidates that could still be useful, and discards anyone who would be hidden behind a newcomer.

Practical use cases

  • Web app: Nearest taller building to the left. A property-listing map shows the nearest taller building to the left of each plot, which might block its sunlight. Instead of looking left from each plot repeatedly, a stack keeps only candidate buildings that are not hidden. Each new plot reads the answer from the top of the stack.
  • Web app: Last day a share was cheaper. A stock page wants to show, for today's price, when it was last lower, for example "lowest since 12 March". The stack drops all older prices that are higher than today, so the first remaining one is the answer, found without scanning the whole history.
  • System: Stock span and histogram building blocks. Problems like stock span, largest rectangle, and trapped rain water all start by finding the nearest bigger or smaller item on each side. Parsers use the same idea to find the nearest enclosing block, so one sweep over the text is enough.

The story: The Nearest Taller Friend

At assembly, Mrs. Sharma's class stood in one long queue. Aarav, who stood near the middle, wondered, "Who is the nearest classmate before me who is shorter than I am?" Zoya asked the opposite question: "And who is the nearest taller one before me?" These are previous smaller and previous greater.

The old way was to turn around and scan the line backwards for each student: slow and repetitive. Mira offered a calmer way: let the queue walk past one by one, and keep a stack of "possible answers" for whoever comes next.

When a new student arrives, throw away every candidate on top who is not shorter: they are taller or equal, so they cannot be the nearest shorter friend for the newcomer, and because the newcomer stands in front of them, they can never be the answer for later students either. Whoever remains on top is the answer. Then the newcomer becomes a candidate.

For the previous greater question, the same pattern holds with the comparison turned upside down. One loop, one stack, and each student enters and leaves it at most once.

How to spot this problem, and where you need it

For each position you need the closest earlier item that is larger or smaller, for example the last time a value was this low, and scanning back every time is too slow.

Signs you need it

  • The text says "previous greater", "previous smaller", "last time it was lower", "nearest taller to the left" or "since when".
  • You scan backward from each position until the condition holds, producing slow nested loops on long histories.
  • The answer for one item can be reused to help answer the next item, such as in a rolling chart.

Where to use it in a project

  • Stock and price pages saying "lowest since..." or "highest since...".
  • Time-series dashboards that compute how long a value has been the best.
  • First step of histogram and span problems that need boundaries on both sides.

The solution

Move left to right with a stack of earlier candidates. For each new item, pop candidates that are not larger than it (for previous greater), since the new item will hide them from everything later. After popping, the top of the stack, if any, is the nearest greater item on the left. Then push the new item. Every item is pushed and popped once.

Payoff: Before: scanning back through thousands of earlier days for each one. After: one pass in which each day is touched about twice.

Explain it like I am 8

You are in a queue and look back for the first kid shorter than you. A kid who is taller than the newcomer, and stands behind the newcomer, will be hidden by them for everyone after. So we forget those taller kids. The kid left at the end of our list is your nearest shorter friend.

How it works, step by step

  1. Walk left to right with an empty stack.
  2. For previous smaller: pop while the top is greater than or equal to the current item.
  3. Read the answer: the stack top if there is one, otherwise -1.
  4. Push the current item for the benefit of the items after it.
  5. For previous greater, pop while the top is smaller than or equal to the current item. Everything else is the same.

The code in four languages

PHP

<?php
// Generic "previous nearest" finder. $drop says when a stack top is useless.
function previous(array $nums, callable $drop): array {
    $answer = [];
    $stack = [];
    foreach ($nums as $x) {
        while ($stack && $drop(end($stack), $x)) {
            array_pop($stack);                       // useless candidates leave
        }
        $answer[] = $stack ? end($stack) : -1;       // nearest survivor (or -1)
        $stack[] = $x;
    }
    return $answer;
}

$queue = [2, 5, 3, 7, 4, 6];
$smaller = previous($queue, fn($top, $x) => $top >= $x);   // pop tops that are not smaller
$greater = previous($queue, fn($top, $x) => $top <= $x);   // pop tops that are not greater
echo 'previous smaller: ' . implode(', ', $smaller) . PHP_EOL;   // -1, 2, 2, 3, 3, 4
echo 'previous greater: ' . implode(', ', $greater) . PHP_EOL;   // -1, -1, 5, -1, 7, 7

JavaScript

// Generic "previous nearest" finder. drop says when a stack top is useless.
function previous(nums, drop) {
  const answer = [];
  const stack = [];
  for (const x of nums) {
    while (stack.length && drop(stack[stack.length - 1], x)) {
      stack.pop();                                   // useless candidates leave
    }
    answer.push(stack.length ? stack[stack.length - 1] : -1);   // nearest survivor (or -1)
    stack.push(x);
  }
  return answer;
}

const queue = [2, 5, 3, 7, 4, 6];
const smaller = previous(queue, (top, x) => top >= x);   // pop tops that are not smaller
const greater = previous(queue, (top, x) => top <= x);   // pop tops that are not greater
console.log('previous smaller: ' + smaller.join(', '));  // -1, 2, 2, 3, 3, 4
console.log('previous greater: ' + greater.join(', '));  // -1, -1, 5, -1, 7, 7

Java

import java.util.*;
import java.util.function.BiPredicate;

public class Main {
    // Generic "previous nearest" finder. drop says when a stack top is useless.
    static List<Integer> previous(int[] nums, BiPredicate<Integer, Integer> drop) {
        List<Integer> answer = new ArrayList<>();
        Deque<Integer> stack = new ArrayDeque<>();
        for (int x : nums) {
            while (!stack.isEmpty() && drop.test(stack.peek(), x)) {
                stack.pop();                             // useless candidates leave
            }
            answer.add(stack.isEmpty() ? -1 : stack.peek());   // nearest survivor (or -1)
            stack.push(x);
        }
        return answer;
    }

    public static void main(String[] args) {
        int[] queue = {2, 5, 3, 7, 4, 6};
        var smaller = previous(queue, (top, x) -> top >= x);   // pop tops that are not smaller
        var greater = previous(queue, (top, x) -> top <= x);   // pop tops that are not greater
        System.out.println("previous smaller: " + String.join(", ", smaller.stream().map(String::valueOf).toList()));   // -1, 2, 2, 3, 3, 4
        System.out.println("previous greater: " + String.join(", ", greater.stream().map(String::valueOf).toList()));   // -1, -1, 5, -1, 7, 7
    }
}

Go

package main

import (
	"fmt"
	"strconv"
	"strings"
)

// previous is a generic "previous nearest" finder. drop says when a stack top is useless.
func previous(nums []int, drop func(top, x int) bool) []int {
	var answer, stack []int
	for _, x := range nums {
		for len(stack) > 0 && drop(stack[len(stack)-1], x) {
			stack = stack[:len(stack)-1] // useless candidates leave
		}
		if len(stack) > 0 {
			answer = append(answer, stack[len(stack)-1]) // nearest survivor
		} else {
			answer = append(answer, -1) // or -1
		}
		stack = append(stack, x)
	}
	return answer
}

func join(nums []int) string {
	parts := make([]string, len(nums))
	for i, v := range nums {
		parts[i] = strconv.Itoa(v)
	}
	return strings.Join(parts, ", ")
}

func main() {
	queue := []int{2, 5, 3, 7, 4, 6}
	smaller := previous(queue, func(top, x int) bool { return top >= x }) // pop tops that are not smaller
	greater := previous(queue, func(top, x int) bool { return top <= x }) // pop tops that are not greater
	fmt.Println("previous smaller: " + join(smaller))                     // -1, 2, 2, 3, 3, 4
	fmt.Println("previous greater: " + join(greater))                     // -1, -1, 5, -1, 7, 7
}

Time: O(n) · Extra space: O(n). One pass; each item is pushed once and popped at most once.

Watch out for

  • Reading the answer after pushing the current item (you would just get the item itself).
  • Choosing the wrong comparison: previous smaller pops tops that are bigger or equal; previous greater pops tops that are smaller or equal.
  • Mixing up "next" and "previous": next looks right of the item, previous looks left. The stack idea is identical.

Quick check

  1. For [2, 5, 3, 7, 4, 6], what is the previous smaller of 3?
    • 2
    • -1
    • 5
  2. For previous smaller, which tops do you pop when x arrives?
    • Tops smaller than x
    • Tops greater than or equal to x
    • No one, just push
  3. What is the answer when the stack is empty after popping?
    • The current item
    • 0
    • -1 (no such element)