AlgoTales · Roadmap

Next smaller element

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

Where you will meet this in real life

Next smaller element finds, for each item, the first item after it that is smaller. It is the mirror of next greater: you keep a stack of items still waiting for a smaller value, and each new smaller value resolves several of them at once.

Practical use cases

  • Web app: A price-drop watcher for vegetable rates. A grocery app records daily tomato prices and wants to show, for each day, when the price next dipped below it. Instead of scanning forward each time, a stack holds days still waiting for a cheaper day. A new low price answers all higher waiting days together.
  • Web app: Flight fare tracker. A travel site displays, for each date on a fare calendar, the next date with a cheaper ticket. The stack sweep produces this hint for a full year of dates in one quick pass, so the calendar opens without delay.
  • System: Histograms, compilers and rain water. The same idea underpins classic problems such as the largest rectangle in a bar chart and how much rain a landscape of bars can hold. Because one cheap sweep answers every bar at once, these problems avoid many repeated lookups.

The story: Waiting for Cheaper Tomatoes

Mira's mother loved a bargain. Every day she asked the vegetable seller the price of tomatoes, and wrote it in a notebook: 40, 80, 50, 20, 250 rupees per kilo. "On which day will tomatoes become cheaper than today?" she wondered, for each day.

Mira tried the slow way first: stand on a day, then read ahead until you find a lower price. It worked, but for a month of prices it was a lot of reading. Then Mira had an idea: read the notebook from the end, backwards.

She kept a small stack of "candidate" prices. For each day, she popped any candidate that was not cheaper than today's price, because such a candidate can never be useful for today or for any earlier day, since today is already cheaper or equal. Whatever stayed on top was the nearest cheaper price on the right. Then she pushed today's price for the earlier days to use.

Mira found a result for every day in one backwards sweep. This is the next smaller element problem, the mirror twin of the next greater element: same stack idea, only the comparison is flipped, and here we went right-to-left for a change.

How to spot this problem, and where you need it

You want, for every value in a series, the next value that is lower, to show price drops or find boundaries, and you do not want to look ahead separately for every entry.

Signs you need it

  • The wording is "next smaller", "next cheaper day", "first drop below", or "nearest lower bar on the right".
  • You have a calendar, chart or table where each row needs a hint pointing to the next lower row.
  • A bar-chart or histogram problem needs to know where each bar stops being the minimum.

Where to use it in a project

  • Fare, grocery and stock price calendars with next-cheaper hints.
  • Histogram and bar-chart code that needs width limits for each bar.
  • Alert rules such as "tell me when the price falls below today's".

The solution

Go through the list once keeping a stack of positions whose next smaller value is not yet known, with the stack's values kept in rising order. For each new value, while the top has a larger value than the new one, pop it and record the new value as its answer. Push the new position. Whatever remains has no smaller value later.

Payoff: Before: a nested loop over a year of daily prices. After: a single sweep of about 730 steps, and the calendar renders instantly.

Explain it like I am 8

Imagine standing in a line holding your price card, and you look to your right for the first card with a smaller number. Starting from the far right and moving left, you remember a short list of "useful" cards. A card that is bigger than the newcomer is never useful again, so you throw it away.

How it works, step by step

  1. Start at the right end with an empty stack and an answer list.
  2. For each item, moving left, pop every stack top that is not smaller than the current item (greater or equal). They can never answer for this item or anything to its left.
  3. Read the answer: if the stack is empty it is -1, otherwise it is the top.
  4. Push the current item. It is a candidate for the items to its left.
  5. Alternative: you can also walk left to right like the next greater lesson, popping while the top is bigger than the newcomer.

The code in four languages

PHP

<?php
// For each number, find the next smaller number to its right (or -1).
// We walk from the right end and keep a stack of candidates.
function nextSmaller(array $nums): array {
    $n = count($nums);
    $answer = array_fill(0, $n, -1);
    $stack = [];                                     // values seen on the right

    for ($i = $n - 1; $i >= 0; $i--) {
        // anything not smaller than nums[i] is useless from now on
        while ($stack && end($stack) >= $nums[$i]) {
            array_pop($stack);
        }
        $answer[$i] = $stack ? end($stack) : -1;     // the top is the nearest smaller
        $stack[] = $nums[$i];
    }
    return $answer;
}

echo implode(', ', nextSmaller([40, 80, 50, 20, 250])) . PHP_EOL;   // 20, 50, 20, -1, -1

JavaScript

// For each number, find the next smaller number to its right (or -1).
// We walk from the right end and keep a stack of candidates.
function nextSmaller(nums) {
  const n = nums.length;
  const answer = new Array(n).fill(-1);
  const stack = [];                                  // values seen on the right

  for (let i = n - 1; i >= 0; i--) {
    // anything not smaller than nums[i] is useless from now on
    while (stack.length && stack[stack.length - 1] >= nums[i]) {
      stack.pop();
    }
    answer[i] = stack.length ? stack[stack.length - 1] : -1;   // the top is the nearest smaller
    stack.push(nums[i]);
  }
  return answer;
}

console.log(nextSmaller([40, 80, 50, 20, 250]).join(', '));   // 20, 50, 20, -1, -1

Java

import java.util.*;

public class Main {
    // For each number, find the next smaller number to its right (or -1).
    // We walk from the right end and keep a stack of candidates.
    static int[] nextSmaller(int[] nums) {
        int n = nums.length;
        int[] answer = new int[n];
        Arrays.fill(answer, -1);
        Deque<Integer> stack = new ArrayDeque<>();       // values seen on the right

        for (int i = n - 1; i >= 0; i--) {
            // anything not smaller than nums[i] is useless from now on
            while (!stack.isEmpty() && stack.peek() >= nums[i]) {
                stack.pop();
            }
            answer[i] = stack.isEmpty() ? -1 : stack.peek();   // the top is the nearest smaller
            stack.push(nums[i]);
        }
        return answer;
    }

    public static void main(String[] args) {
        int[] result = nextSmaller(new int[]{40, 80, 50, 20, 250});
        System.out.println(Arrays.toString(result));     // [20, 50, 20, -1, -1]
    }
}

Go

package main

import "fmt"

// nextSmaller finds, for each number, the next smaller number to its right (or -1).
// We walk from the right end and keep a stack of candidates.
func nextSmaller(nums []int) []int {
	n := len(nums)
	answer := make([]int, n)
	var stack []int // values seen on the right

	for i := n - 1; i >= 0; i-- {
		// anything not smaller than nums[i] is useless from now on
		for len(stack) > 0 && stack[len(stack)-1] >= nums[i] {
			stack = stack[:len(stack)-1]
		}
		if len(stack) > 0 {
			answer[i] = stack[len(stack)-1] // the top is the nearest smaller
		} else {
			answer[i] = -1
		}
		stack = append(stack, nums[i])
	}
	return answer
}

func main() {
	fmt.Println(nextSmaller([]int{40, 80, 50, 20, 250})) // [20 50 20 -1 -1]
}

Time: O(n) · Extra space: O(n). Each value is pushed once and popped at most once. The slow way (scan ahead for each item) is O(n²).

Watch out for

  • Popping only strictly greater values. Equal values are not "smaller", so pop on greater or equal when scanning from the right.
  • Reading the answer after pushing the current value. Read the top first, then push.
  • Mixing directions: scanning left-to-right needs the "pop while top is bigger" form; scanning right-to-left needs "pop while top is not smaller".

Quick check

  1. What is the next smaller element for each of [40, 80, 50, 20, 250]?
    • [20, 50, 20, -1, -1]
    • [80, 250, 250, 250, -1]
    • [20, 20, 20, -1, -1]
  2. Scanning from the right, which stack tops do you pop for the current value x?
    • Those smaller than x
    • Those greater than or equal to x
    • Only the equal ones
  3. What is the time complexity?
    • O(2ⁿ)
    • O(n²)
    • O(n)