Skip to content

Stacks and Ring Buffers: Open Items and the Last k Values

How stacks track what is still open and ring buffers keep the last k values of a stream, with O(1) operations, edge cases and code in TS, Python and PHP.

12 min readTime: O(1) per push, pop or stream value; O(n) for n eventsMemory: O(k) for the ring buffer, O(n) worst case for a stackAlgorithmsStacks and ring buffers

Two small structures cover a surprising number of interview problems. A stack answers "what is the most recent thing still waiting to be closed?" A ring buffer answers "what were the last k things that happened?" Both run in O(1) per operation on a plain array, and both have edge cases that interviewers probe on purpose. This guide builds the intuition for each one and then traces a problem that needs both at once: an undo history capped at k entries. Last in, first out, but the oldest entries fall off when the buffer is full.

The intuition

The picture to keep in your head.

Think of a stack as a list of promises you have not kept yet. Every opening bracket, start tag, function call or edit adds a promise. A closing event can only settle the most recent unsettled promise, because anything older is still nested inside it. That is why the top of the stack is the only element you ever need to look at, and why pushing and popping at the end of an array is enough. You never search, never delete from the middle, so a whole text is processed in one pass.

The stack's state at any moment is the answer to "what is still open?" When the input ends, an empty stack means everything was closed. A close that arrives while the stack is empty means something was closed that was never opened. Those two checks are where most bugs live.

A ring buffer is a fixed array of k slots plus a write index that wraps around with i % k. New values overwrite the oldest slot, so the array always holds the last k values without shifting anything. The slot you are about to overwrite is exactly the value leaving the window, which is what makes running aggregates cheap: add the newcomer, subtract the evicted value, done in O(1).

The two ideas combine naturally. If you keep a stack inside a ring buffer, pushes wrap around and silently drop the oldest entry once k are stored, while pops still take the newest. That is a bounded undo history: you can always undo the latest action, but memory never grows past k.

Step by step

Small, safe steps, with the tests passing after each.

  1. Step 1: Decide what an open item is

    Write down what gets pushed: a bracket character, a tag name, an index into the input, an edit record. Push whatever you need later to verify or reverse the close. Pushing indices instead of values is often smarter because you can recover both the value and its position.

  2. Step 2: Handle a close against the top only

    On a closing event, look at the top of the stack. If the stack is empty, the input is invalid or there is nothing to undo; return that explicitly instead of reading an undefined value. If the top does not match, fail. Otherwise pop.

  3. Step 3: Check the leftovers at the end

    After the loop, items still on the stack were opened and never closed. For validation problems the answer is only true when the stack is empty. For simplification problems the remaining stack is the result, read bottom to top.

  4. Step 4: Size the ring buffer and wrap the index

    Allocate k slots once. Keep a write index and advance it with (i + 1) % k. When stepping backwards, use (i - 1 + k) % k, because in JavaScript and PHP the remainder of a negative number is negative.

  5. Step 5: Track how many slots are real

    Keep a count capped at k. Until count reaches k, the window is partial: an average must divide by count, not k, and slots beyond count hold nothing meaningful. Once full, the slot at the write index is the oldest value.

  6. Step 6: Maintain aggregates incrementally

    For a running sum, subtract the value in the slot before overwriting it, then add the new one. Each update is O(1) instead of re-summing k values. Only do this for invertible aggregates such as sum or count; a maximum needs a different structure.

What it costs

Time and memory, and why.

Time
O(1) per push, pop or stream value; O(n) for n events
Memory
O(k) for the ring buffer, O(n) worst case for a stack

Push and pop at the end of an array touch one slot and move one index, so they are constant time (amortised for a growable array, strictly for a fixed one). A single pass over n characters or events therefore costs O(n), compared with O(n^2) if you repeatedly search for and delete matched pieces. An unbounded stack can hold every input element, as in a run of only opening brackets, hence O(n) space. A ring buffer allocates k slots once and never grows, and a running aggregate needs only one extra number, so the moving statistic costs O(1) time per value and O(k) memory.

A traced example

A small input, followed step by step.

Tilemint, a pixel-art app, keeps at most k = 3 undo entries for paint strokes. Run: push s1, push s2, push s3, push s4, pop, pop, push s5, pop, pop, pop. Slots are shown as [slot0, slot1, slot2], top is the next slot to write.

  1. 1slots [_, _, _], top 0, count 0Empty history. Any pop now must return null.
  2. 2slots [s1, _, _], top 1, count 1push s1 writes slot 0 and advances top.
  3. 3slots [s1, s2, _], top 2, count 2push s2 writes slot 1.
  4. 4slots [s1, s2, s3], top 0, count 3push s3 writes slot 2; top wraps to (2 + 1) % 3 = 0. The buffer is full.
  5. 5slots [s4, s2, s3], top 1, count 3push s4 overwrites slot 0, so s1 is gone for good. count stays capped at 3; the oldest entry, s2, now sits at index top.
  6. 6slots [_, s2, s3], top 0, count 2, returned s4pop moves top back to (1 - 1 + 3) % 3 = 0 and returns the newest stroke.
  7. 7slots [_, s2, _], top 2, count 1, returned s3pop steps back to (0 - 1 + 3) % 3 = 2. Without the + 3, JavaScript and PHP would compute -1.
  8. 8slots [_, s2, s5], top 0, count 2push s5 reuses slot 2 and wraps top to 0.
  9. 9slots [_, s2, _], top 2, count 1, returned s5pop returns the stroke just pushed: last in, first out.
  10. 10slots [_, _, _], top 1, count 0, returned s2pop returns s2, the oldest surviving stroke.
  11. 11slots [_, _, _], top 1, count 0, returned nullcount is 0, so pop refuses instead of reading a stale slot. s1 was evicted by s4 and cannot be undone.

Result: Undo returns s4, s3, s5, s2, then null. Memory never exceeds 3 slots and every operation is O(1).

The code

The same solution in TypeScript, Python and PHP.

// Undo history that keeps only the last k entries.
// Stack order for pops, ring buffer storage for pushes.
class BoundedUndo<T> {
  private slots: (T | undefined)[];
  private top = 0; // next slot to write
  private count = 0; // real entries stored, never above k

  constructor(private readonly k: number) {
    if (k < 1) throw new Error("k must be at least 1");
    this.slots = new Array<T | undefined>(k).fill(undefined);
  }

  push(x: T): void {
    this.slots[this.top] = x; // overwrites the oldest entry when full
    this.top = (this.top + 1) % this.k;
    this.count = Math.min(this.count + 1, this.k);
  }

  pop(): T | null {
    if (this.count === 0) return null; // nothing left to undo
    this.top = (this.top - 1 + this.k) % this.k; // + k avoids a negative index
    const x = this.slots[this.top] as T;
    this.slots[this.top] = undefined;
    this.count--;
    return x;
  }

  size(): number {
    return this.count;
  }
}

const history = new BoundedUndo<string>(3);
for (const s of ["s1", "s2", "s3", "s4"]) history.push(s);
console.log(history.pop()); // s4
console.log(history.pop()); // s3
history.push("s5");
console.log(history.pop()); // s5
console.log(history.pop()); // s2
console.log(history.pop()); // null

Variants

Shapes the same idea takes.

  • Stack of indices

    When: You need positions as well as values, for example the length of the longest valid segment or which character is unmatched.

    Push the index of each open item rather than the character. On a close you pop and can compute the distance to the new top, or report the exact offset of an error. Seeding the stack with a sentinel index such as -1 often removes an empty-stack special case.

  • Monotonic stack

    When: For each element you need the next greater or next smaller element, such as how many days until a warmer reading.

    Keep the stack sorted by popping every element that the new one dominates; each popped element has just found its answer. Every index is pushed and popped at most once, so the whole pass is O(n) even though there is a loop inside the loop.

  • Ring buffer as a fixed queue

    When: You need FIFO order with a hard capacity, for example a producer writing log lines and a consumer reading them.

    Store a head index and a count. Enqueue writes at (head + count) % k, dequeue reads at head and advances it. Decide upfront whether a full buffer rejects new items or overwrites the oldest; interviewers like to ask which one fits.

  • Windowed aggregate with running state

    When: A stream asks for a sum, count or average over the last k values.

    Before writing into the slot, subtract its old value from the running total, then add the new one. Divide by min(count, k) while the window is filling. Sums and counts are invertible, which is what makes the O(1) update valid.

  • Monotonic deque for window max or min

    When: The window statistic is a maximum or minimum, which cannot be undone by subtraction.

    Keep a deque of indices with decreasing values. Drop indices that fall out of the window from the front and dominated values from the back. Each index enters and leaves once, so it is O(1) amortised per value and O(k) memory.

Common mistakes

What usually goes wrong and how to avoid it.

  • Avoid

    Popping or peeking an empty stack when a close arrives first.

    Better

    Check the size before every pop and treat an empty stack on a close as an immediate failure or a null result. In Python [].pop() raises, and in JavaScript [].pop() silently returns undefined, which hides the bug.

  • Avoid

    Returning true as soon as the loop finishes without checking for leftovers.

    Better

    An input like three opening brackets never triggers a mismatch. The final answer must also require that the stack is empty.

  • Avoid

    Computing the previous slot with (i - 1) % k in JavaScript or PHP.

    Better

    Both languages keep the sign of the dividend, so -1 % 3 is -1. Write (i - 1 + k) % k. Python returns 2 either way, but using the same expression everywhere avoids surprises.

  • Avoid

    Dividing the window sum by k before k values have arrived.

    Better

    Keep a count and divide by min(count, k). With values 4 and 8 and k = 5 the average is 6, not 2.4.

  • Avoid

    Implementing the window as a dynamic list with shift or pop(0).

    Better

    Removing from the front shifts every element, which is O(k) per value. Overwrite slots in a fixed array or use a real deque such as collections.deque.

  • Avoid

    Forgetting to subtract the overwritten value from the running sum.

    Better

    Read the slot first, subtract it, then write the new value and add it. Reversing the order subtracts the newcomer and corrupts the total.

How to recognise it

Clues in a problem statement that call for it.

  • The input has openers and closers that must nest: brackets, tags, BEGIN and END blocks, function calls.
  • Something must be undone or reversed in the opposite order it was done.
  • Adjacent items cancel or merge, and removing a pair can expose a new pair.
  • The problem says "last k", "most recent k" or "sliding window" over a stream you cannot store entirely.
  • Memory must stay bounded no matter how long the stream runs.
  • A naive solution rescans the whole window or rescans the string after every deletion.

Common questions

Short answers to the usual doubts.

Why is a stack the right structure for nested brackets rather than counters?

A counter per bracket type tells you how many are open, but not in what order. The string ([)] has balanced counts yet is invalid because the square bracket closes while the parenthesis opened after it is still open. Only the most recent unclosed opener can be legally closed, and that is exactly the top of a stack. With a single bracket type a counter is enough, and saying so earns points.

Is pushing to a dynamic array really O(1)?

Amortised, yes. Occasionally the array doubles its capacity and copies everything, but the total copying across n pushes is proportional to n, so the average per push is constant. Popping from the end never copies. A ring buffer avoids even the occasional resize because its size is fixed at k.

How do I tell the oldest value in a full ring buffer?

If you write at index top and then advance it, the slot at top after a write holds the oldest value once the buffer is full. Before it is full, the oldest value is at index 0, or more generally at (top - count + k) % k, which covers both cases.

Should a full bounded buffer reject or overwrite?

It depends on what losing data means. For undo history or a moving statistic, dropping the oldest entry is the point, so overwrite. For a work queue where every item must be processed, reject or block the producer instead. State your choice and the reason before coding.

Can I just use a language's built-in deque instead of writing a ring buffer?

Usually yes, and collections.deque(maxlen=k) in Python behaves like an overwriting ring buffer. In an interview, use it if allowed but be ready to explain the index arithmetic underneath, because a follow-up often asks you to implement it with a plain array.

Now, practise it

Put it to work straight away.

Tests, exercises and problems that use what you've just read.