Bitpath

Data Structures

The containers behind most algorithms. Learn what stacks, queues and linked lists make cheap and what they make expensive, then open up a hash table and build one yourself.

  • Intermediate
  • 4 units, 12 lessons, 150 exercises
  • Python, JavaScript or TypeScript
  • Builds on Algorithm Foundations

Unit 01 · 3 lessons

Stacks

Use last-in, first-out order to match, undo and evaluate

  1. > start01Last in, first out
  2. 02Matching brackets
  3. BOSSEvaluate and track
Unit prize
  1. 01
    Last in, first out

    Push, pop and peek at the end of an array

  2. 02
    Matching brackets

    Push openers, pop on closers, end empty

  3. BOSS
    Evaluate and track

    A postfix calculator and a stack that knows its minimum

Read the unit guide

A stack is a pile: you add to the top and you take from the top. Last in, first out (LIFO). It has three operations, all O(1): push (add on top), pop (remove the top and return it) and peek (read the top without removing it).

An array is all you need, as long as the top of the stack is the end of the array, because adding and removing at the end never shifts anything. In Python that is append, pop() and stack[-1]. In JavaScript and TypeScript it is push, pop() and stack.at(-1).

Reach for a stack whenever the most recent thing matters first: undo, the back button, function calls, anything nested. For brackets, push each opener; on a closer, pop and check that the two match. At the end the stack must be empty.

Two failure cases come up everywhere. Popping an empty stack: Python raises IndexError, JavaScript quietly returns undefined, so check for empty first. And leftovers: a stack that is not empty at the end means unfinished business, such as an unclosed bracket.

Stacks also evaluate expressions. In postfix notation (2 3 4 * +) numbers are pushed, and an operator pops two numbers, applies itself and pushes the result. The first pop is the right-hand operand, which matters for subtraction and division.

A stack can carry extra facts at no cost. Store beside each value the minimum of everything at or below it, and the smallest item is readable from the top in O(1).

Unit 02 · 3 lessons

Queues and deques

Serve items in arrival order without paying to shift them

  1. 01First in, first out
  2. 02Both ends
  3. BOSSA queue from two stacks
Unit prize
  1. 01
    First in, first out

    Why the front of an array is expensive, and what to do instead

  2. 02
    Both ends

    Deques, a recent-events counter and the circular buffer

  3. BOSS
    A queue from two stacks

    Pour once, pop many times: amortised O(1)

Read the unit guide

A queue is a line of people: you join at the back and leave from the front. First in, first out (FIFO). Use one whenever things must be handled in the order they arrived: print jobs, requests, and later the breadth-first searches of the Trees and Graphs roadmaps.

The trap is the front of an array. Removing index 0 makes every other item move down one place, so list.pop(0) in Python and shift() in JavaScript are O(n). Emptying a queue of n items that way costs O(n²).

There are two standard fixes. Python has collections.deque, which is O(1) at both ends. JavaScript and TypeScript have no built-in queue, so you keep a head index and move it forward instead of removing anything. A circular buffer is the tidy version of that idea: a fixed array used as a ring, with indexes wrapped by % capacity.

A deque (say "deck") is a double-ended queue: add and remove at either end in O(1). It is not fast in the middle. It fits "keep the recent ones" problems: new items join at the back and expired items leave from the front.

You can also build a queue from two stacks. New items are pushed onto an in-stack. To dequeue, pop the out-stack; when it is empty, first pour the whole in-stack into it, which reverses the items so the oldest ends up on top. Pour only when the out-stack is empty.

That queue shows amortised cost. One dequeue can take O(n), but each item is poured exactly once in its life, so n operations cost O(n) in total: O(1) each on average.

Unit 03 · 3 lessons

Linked lists

Follow, rewire and reverse a chain of nodes

  1. 01Nodes and pointers
  2. 02Insert and delete
  3. BOSSReverse and runner
Unit prize
  1. 01
    Nodes and pointers

    A chain you can only enter at the head

  2. 02
    Insert and delete

    The order of pointer updates, and the dummy head

  3. BOSS
    Reverse and runner

    Three pointers to reverse, two speeds to find the middle

Read the unit guide

A linked list is a chain of nodes. Each node holds a value and a pointer to the next node; the last node points to nothing. You keep one variable, the head, and everything else is reached by following pointers from it.

The trade against an array is exact. An array reads position k in O(1) but inserting at the front shifts everything, O(n). A linked list inserts at the front with one new node, O(1), but reading position k means following k pointers, O(k). Even its length takes a full walk unless you keep a counter.

To walk a list, use a separate variable: node = head, then node = node.next until it is empty. Never move head itself, because it is your only way in.

Inserting and deleting are pointer assignments, and their order matters. To insert X after A: first point X at A's next node, then point A at X. Done the other way round, X points at itself and the rest of the list is lost. To delete the node after A: A.next = A.next.next.

The head has no node before it, which makes it a special case. A dummy node placed in front removes the special case: every real node now has a predecessor, and the finished list starts at dummy.next.

Two patterns to memorise. Reversal walks with three pointers: save the next node, point the current node back at prev, then move both forward. The runner uses a slow pointer (one step) and a fast pointer (two steps): when fast reaches the end, slow is at the middle, and if the two ever meet, the list has a cycle.

Unit 04 · 3 lessons

Hash tables

Open up the map: buckets, collisions, resizing, and why it is O(1)

  1. 01Hash, then bucket
  2. 02Load factor and resizing
  3. BOSSBuild a hash map
Unit prize
  1. 01
    Hash, then bucket

    From a key to an array index, and what happens when two keys collide

  2. 02
    Load factor and resizing

    Why tables double, and what "amortised O(1)" is promising

  3. BOSS
    Build a hash map

    Write get and put with chaining, then see how keys can go wrong

Read the unit guide

A hash table is an array of buckets. To store a key it computes a number from the key, the hash, and takes hash % capacity to pick a bucket. The same key always lands in the same bucket, so a lookup goes straight there instead of searching.

Different keys can land in the same bucket. That is a collision, and it is normal: there are more possible keys than buckets. With chaining, each bucket holds a short list of key-value pairs, and a lookup scans only that one chain.

The load factor is items divided by buckets, which is the average chain length. When it passes a threshold (0.75 is common) the table doubles its capacity and rehashes every pair, because hash % capacity changes when the capacity does.

One resize costs O(n), but doubling makes resizes rare, so an insert is O(1) amortised. Lookups are O(1) on average. The worst case is still O(n): a bad hash function can send every key to one bucket, and then the table is one long list.

put hashes to a bucket, scans the chain, replaces the value if the key is already there and appends a new pair otherwise. get hashes, scans and returns the value, or nothing.

Keys must not change while they are in the table: the pair would stay in a bucket chosen from the old value, where no lookup will look. Use strings, numbers or tuples. Python's map is dict; in JavaScript and TypeScript prefer Map to a plain object, which turns every key into a string.

Learn Data Structures on your phone.

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy