Stacks

Last in, first out · Part of Lists, stacks and hash

Key idea

Practice

6 questions · about 3 min

Explained step by step

Stack

A stack follows the rule "last in, first out". It's like a stack of plates: if you can only move one at a time, to reach the bottom one you have to remove all the ones above. The end where you work is called the top. Adding on top is called push, removing the top one is called pop and looking at the top one without removing it is called peek.

To trace a stack by hand, you write down what's in it after each step, with the top on the right. Push adds on the right; pop removes the rightmost. For example: push A, push B, pop (B comes out), push C, pop (C comes out), pop (A comes out). The elements come out in the order B, C, A. It's exactly what interviews ask to see if you understand the rule.

A stack can be built with an array or a linked list, hiding the operations that aren't stack operations. With an array, the top is the end: push adds at the end and pop removes the last, both O(1); if it fills up, the dynamic array grows and that push costs O(n). With a linked list, the top is the head: push inserts at the start and pop removes the head, always O(1), but each node takes more memory.

Stacks show up everywhere. The browser's "Back" button pushes each page you leave; going back pops the last one. Undo in an editor pushes each change and undo pops the last. And the system's call stack pushes a frame for each function called and pops it when it finishes, recursive calls included.

A classic interview problem: check whether the brackets in a text are properly closed, with (), [] and {}. You walk the text: each opening is pushed; each closing must match the top, which is popped. If it doesn't match, or if the stack isn't empty at the end, it's wrong. It works because the last one opened is the first one that has to close: exactly the stack rule.

Call stack

Recursion and stacks are closely connected. Each recursive call pushes a frame onto the call stack, and every time one finishes, it's popped: the last one called is the first to finish. That's why any recursion can be rewritten with a loop and your own stack. It's useful when the recursion would be so deep it would overflow the system's stack.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

Last in, first out