AlgoTales · Roadmap

Min stack / Max stack

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

Where you will meet this in real life

A min stack is a normal stack that can also tell you the smallest item currently inside it instantly. Beside every item it remembers the smallest value up to that point, so removing the top automatically restores the previous minimum. A max stack does the same for the largest.

Practical use cases

  • Web app: Lowest price in the current cart. A shopping cart page shows "cheapest item in your cart" while shoppers add and remove products. Rescanning every item on each click wastes work. A min stack keeps the cheapest value beside each item, so the display updates immediately when an item is added or removed.
  • Web app: Live high and low on a trading dashboard. A dashboard shows the highest and lowest price since a session began while new prices arrive and the user can undo the latest few. A max stack and a min stack give the current high and low instantly, with no rescanning of the session.
  • System: Game state history and streaming stats. Games that allow undo and tools that watch live sensor feeds need statistics that stay correct when the latest item is removed. Storing the running minimum or maximum beside each entry is the neat way to do this without recalculating, and it takes only a little extra memory.

The story: The Cheapest Bill in the Pile

Raju kept the day's bills on a spike near his chai stall: each new bill was pushed on top, and when someone asked to see the last bill, he pulled the top one. The owner, a keen bargain hunter, loved to ask, "What is the smallest bill on the spike right now?"

The slow answer was to turn over every bill on the spike and compare them. With 5 bills fine, but with 500 it was a pain, and he was asked this many times a day. Raju needed to answer instantly, without losing the spike's last-in, first-out behaviour.

Mira had an idea: "Keep a second spike. Whenever you push a bill on the main spike, push on the twin spike the smallest amount seen so far at that level." So the twin's top always shows the smallest amount in the pile. When Raju pops a bill from the main spike, he pops the twin as well. The twin's new top is still the correct smallest for the bills that remain, because each level remembered its own situation.

That is a Min Stack: push, pop, peek and getMin, all in constant time. Swap "smallest" for "largest" and you get a Max Stack. Many interview problems ask for exactly this.

How to spot this problem, and where you need it

You use a stack but also need to know the smallest or largest value inside it at any moment, and recalculating by scanning the whole stack after every change is too slow.

Signs you need it

  • The feature says "show the minimum" or "show the maximum" for a collection that changes by adding and undoing the latest item.
  • You call min() or max() over a full array on every click, keystroke or incoming value.
  • The problem is "design a stack that returns the minimum in constant time".

Where to use it in a project

  • Cart or basket summaries showing cheapest or most expensive item while items change.
  • Live dashboards with undo or rollback of the latest readings.
  • Game state and history features that need running statistics.

The solution

Keep a second stack beside the main one. When you push a value, also push the smaller of that value and the current minimum onto the second stack. When you pop, pop both. The top of the second stack is always the current minimum, found without scanning. For a max stack, store the larger one instead.

Payoff: Before: scanning all 1,000 cart items after every click. After: reading one stored number, instantly, however many items exist.

Explain it like I am 8

You have a stack of cards with numbers. Beside each card, on a second stack, you write a sticky note: "the smallest number in the pile up to here". The top sticky note always tells you the smallest number, instantly. When you take a card away, you take its sticky note too.

How it works, step by step

  1. Keep two stacks: the main stack and a twin stack that holds the minimum at every level.
  2. push(x): push x on the main stack. Push min(x, twin top) on the twin (or just x if the twin is empty).
  3. pop(): pop both stacks together and return the main stack's value.
  4. getMin(): peek at the twin's top. No searching needed.
  5. For getMax() keep a third stack with the maximum, or store each entry as a (value, min, max) triple.

The code in four languages

PHP

<?php
// A stack that can also answer "what is the smallest/largest value?" in O(1).
// Each entry remembers [value, min so far, max so far].
class MinMaxStack {
    private array $items = [];

    public function push(int $x): void {
        $min = $this->items ? min($x, end($this->items)[1]) : $x;
        $max = $this->items ? max($x, end($this->items)[2]) : $x;
        $this->items[] = [$x, $min, $max];
    }

    public function pop(): int {
        if (!$this->items) throw new UnderflowException('Stack is empty');
        return array_pop($this->items)[0];
    }

    public function top(): int { return end($this->items)[0]; }
    public function getMin(): int { return end($this->items)[1]; }
    public function getMax(): int { return end($this->items)[2]; }
}

$s = new MinMaxStack();
foreach ([5, 3, 7, 3] as $x) $s->push($x);
echo 'min ' . $s->getMin() . ', max ' . $s->getMax() . PHP_EOL;   // min 3, max 7
$s->pop();
$s->pop();
echo 'min ' . $s->getMin() . ', max ' . $s->getMax() . PHP_EOL;   // min 3, max 5
$s->pop();
echo 'min ' . $s->getMin() . ', max ' . $s->getMax() . PHP_EOL;   // min 5, max 5

JavaScript

// A stack that can also answer "what is the smallest/largest value?" in O(1).
// Each entry remembers [value, min so far, max so far].
class MinMaxStack {
  constructor() { this.items = []; }

  push(x) {
    const last = this.items[this.items.length - 1];
    const min = last ? Math.min(x, last[1]) : x;
    const max = last ? Math.max(x, last[2]) : x;
    this.items.push([x, min, max]);
  }

  pop() {
    if (!this.items.length) throw new Error('Stack is empty');
    return this.items.pop()[0];
  }

  top() { return this.items[this.items.length - 1][0]; }
  getMin() { return this.items[this.items.length - 1][1]; }
  getMax() { return this.items[this.items.length - 1][2]; }
}

const s = new MinMaxStack();
for (const x of [5, 3, 7, 3]) s.push(x);
console.log('min ' + s.getMin() + ', max ' + s.getMax());   // min 3, max 7
s.pop();
s.pop();
console.log('min ' + s.getMin() + ', max ' + s.getMax());   // min 3, max 5
s.pop();
console.log('min ' + s.getMin() + ', max ' + s.getMax());   // min 5, max 5

Java

import java.util.*;

public class Main {
    // A stack that can also answer "what is the smallest/largest value?" in O(1).
    // Each entry remembers value, min so far, max so far.
    static class MinMaxStack {
        record Entry(int value, int min, int max) {}

        private final Deque<Entry> items = new ArrayDeque<>();

        void push(int x) {
            int min = items.isEmpty() ? x : Math.min(x, items.peek().min());
            int max = items.isEmpty() ? x : Math.max(x, items.peek().max());
            items.push(new Entry(x, min, max));
        }

        int pop() {
            if (items.isEmpty()) throw new RuntimeException("Stack is empty");
            return items.pop().value();
        }

        int top() { return items.peek().value(); }
        int getMin() { return items.peek().min(); }
        int getMax() { return items.peek().max(); }
    }

    public static void main(String[] args) {
        MinMaxStack s = new MinMaxStack();
        for (int x : new int[]{5, 3, 7, 3}) s.push(x);
        System.out.println("min " + s.getMin() + ", max " + s.getMax());   // min 3, max 7
        s.pop();
        s.pop();
        System.out.println("min " + s.getMin() + ", max " + s.getMax());   // min 3, max 5
        s.pop();
        System.out.println("min " + s.getMin() + ", max " + s.getMax());   // min 5, max 5
    }
}

Go

package main

import (
	"errors"
	"fmt"
)

// entry remembers the value, the min so far and the max so far.
type entry struct{ value, min, max int }

// MinMaxStack is a stack that can also answer "what is the smallest/largest value?" in O(1).
type MinMaxStack struct {
	items []entry
}

func (s *MinMaxStack) Push(x int) {
	lo, hi := x, x
	if n := len(s.items); n > 0 {
		lo = min(x, s.items[n-1].min)
		hi = max(x, s.items[n-1].max)
	}
	s.items = append(s.items, entry{x, lo, hi})
}

func (s *MinMaxStack) Pop() (int, error) {
	if len(s.items) == 0 {
		return 0, errors.New("Stack is empty")
	}
	last := s.items[len(s.items)-1]
	s.items = s.items[:len(s.items)-1]
	return last.value, nil
}

func (s *MinMaxStack) Top() int { return s.items[len(s.items)-1].value }
func (s *MinMaxStack) Min() int { return s.items[len(s.items)-1].min }
func (s *MinMaxStack) Max() int { return s.items[len(s.items)-1].max }

func main() {
	s := &MinMaxStack{}
	for _, x := range []int{5, 3, 7, 3} {
		s.Push(x)
	}
	fmt.Printf("min %d, max %d\n", s.Min(), s.Max()) // min 3, max 7
	s.Pop()
	s.Pop()
	fmt.Printf("min %d, max %d\n", s.Min(), s.Max()) // min 3, max 5
	s.Pop()
	fmt.Printf("min %d, max %d\n", s.Min(), s.Max()) // min 5, max 5
}

Time: O(1) per operation · Extra space: O(n). Every operation, including getMin and getMax, touches only the top. The price is a little extra memory for the remembered minimum and maximum at each level.

Watch out for

  • Keeping a single "current minimum" variable. When the smallest item is popped you no longer know the next smallest. Each level must remember its own.
  • Forgetting to pop the twin together with the main stack, so the two stacks drift out of step.
  • Scanning the whole stack inside getMin. That works but is O(n), which defeats the purpose.

Quick check

  1. You push 5, 3, 7, 3. What does getMin() return?
    • 3
    • 5
    • 7
  2. Then you pop twice (removing 3 and 7). What is the new minimum?
    • We must search again
    • 3
    • 5
  3. Why is a single "min" variable not enough?
    • Variables cannot hold numbers
    • It is too slow
    • After popping the minimum we cannot recover the next smallest