Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Data Structure Complexity

The full time/space table for every structure you reach for — average and worst case, at a glance. The interview reference.

Big-O describes how an operation’s cost grows with the number of elements n, ignoring constant factors. The table gives average and worst case where they differ, because that gap is often the whole point: a hash table is O(1) on average but O(n) when keys collide, and a plain BST degrades into a linked list on sorted input.

Amortized means averaged over a long sequence of operations, so an occasional expensive step, such as a dynamic array resize, is spread across many cheap ones. Choose a structure by its most frequent operation, then check the worst case if latency matters.

most frequent op?lookup by keymin / maxsorted / rangeprefixhash tableO(1) averagebinary heapO(log n) push/popbalanced BSTO(log n), orderedtrieO(L) per keyhuge, approx ok:Bloom filter, HLLonly k smallest:heap of size kon disk:B+ treestatic set:sorted array
Pick the structure that makes your most frequent operation cheap; the dashed row is the variant to reach for when the data is huge, partial, on disk or never changes.

Linear structures (avg / worst)

Array (static)
access O(1) · search O(n) · insert/delete O(n) · space O(n)
Dynamic array
access O(1) · append O(1) amortized · insert/delete O(n)
Sorted array
binary search O(log n) · insert/delete O(n) — great for read-mostly data
Singly linked list
access/search O(n) · insert/delete at head O(1)
Doubly linked list
same, plus O(1) delete given the node
Stack / Queue
push/pop/enqueue/dequeue O(1)
Ring buffer
fixed capacity; both ends and indexing O(1) — logs, sliding windows

Hash & trees

Hash table
search/insert/delete O(1) avg · O(n) worst (bad hashing)
Hash set
membership O(1) average; iteration order is not something to rely on
Binary search tree
O(log n) avg · O(n) worst (degenerate/unbalanced)
Balanced BST (AVL / RB)
search/insert/delete O(log n) worst — guaranteed
Splay tree · treap
O(log n) amortized (splay) or expected (treap); splaying moves hot keys up
B-tree
O(log n) · high fan-out → few disk reads (DB indexes)
B+ tree
values only in linked leaves: O(log n) lookups plus fast range scans
LSM tree
buffered writes flushed sequentially — cheap inserts; reads may check several levels
Trie
search/insert O(L) in key length L (not n)

Heaps & priority queues

Binary heap
peek O(1) · push/pop O(log n) · build O(n)
Decrease-key
binary heap O(log n) with an index map; Fibonacci heap O(1) amortized
Top-k of a stream
min-heap of size k: O(n log k) time, O(k) space
Running median
two heaps (max below, min above): O(log n) insert, O(1) median

Graphs & strings

Adjacency list
space O(V + E) · edge check O(degree) — the default for sparse graphs
Adjacency matrix
space O(V²) · edge check O(1) — only for dense or small graphs
BFS / DFS
O(V + E) on an adjacency list
Dijkstra (binary heap)
O((V + E) log V); non-negative edge weights only
String concat in a loop
O(n²) with immutable strings — collect parts and join once
Substring search
naive O(n·m); KMP guarantees O(n + m)
Suffix array
build O(n log n) · find a pattern of length m in O(m log n)

Probabilistic & specialized

Skip list
search/insert/delete O(log n) expected · space O(n)
Bloom filter
add/query O(k) hashes · space sublinear · false positives, no false negatives
Count-min sketch
frequency estimates in fixed memory; O(k) per update, never underestimates
HyperLogLog
count distinct with ~1.04/√m error — Redis uses 12 KB for ~0.81%
Fenwick / segment tree
point update + range query O(log n)
Sparse table
static range-min in O(1) after an O(n log n) build; no updates
Interval tree
augmented BST: one overlap in O(log n), all k in O(min(n, k log n))
Union-Find
near O(1) amortized (inverse-Ackermann) with path compression + rank
LRU cache
get/put O(1) — hash map + doubly linked list

Language built-ins

Python list
append and pop() O(1); pop(0), insert(0, x) and x in list are O(n)
Python dict / set
get, set, delete and in are O(1) average; dicts keep insertion order
Java HashMap
O(1) average; crowded buckets become trees, so O(log n) worst for Comparable keys
C++ map · unordered_map
red-black tree O(log n), ordered · hash table O(1) average
JS array shift()
can be O(n); a head index over an array makes a true O(1) queue

Rules of thumb

Need ordering?
Balanced BST / skip list — O(log n) with sorted traversal.
Only membership/lookup?
Hash table — O(1), no order.
Need min/max repeatedly?
Heap — O(log n) push/pop.
Latency SLA?
When the worst case matters, avoid plain hash/BST; use balanced trees or bounded structures.
Need prefix search?
Trie — O(L) per lookup; a sorted array works for static sets
Sliding-window max?
monotonic deque — O(n) total, O(1) amortized per step

Gotchas

Amortized ≠ worst case
a dynamic array append is O(1) amortized but O(n) on the resize
Growth factor
amortized O(1) needs geometric growth (×1.5–2), not a fixed increment
Cache locality
arrays beat linked lists at equal big-O because contiguous memory suits the CPU cache
Hash flooding
crafted colliding keys force O(n) lookups; randomized hashing defends against it

Worked example: a session store with expiry

A login service keeps 10 million sessions. Every request reads one (get), every login writes one with a 30-minute TTL (set), and expired sessions must be removed. Price each design by its most frequent operation:

hash map + sweep every second:  get O(1), but each sweep checks all 10M keys
list sorted by expiry:          expire O(1) at the front, but set shifts O(n)
hash map + min-heap by expiry:  get O(1), set O(log n) ≈ 23 levels, expire O(log n) each

The third combines two rows of this sheet. One wrinkle: refreshing a session changes its expiry, and a binary heap cannot find an arbitrary entry without an index. So leave the old entry in place and skip it when it surfaces, a technique called lazy deletion:

import heapq

class TTLCache:
    def __init__(self):
        self.data = {}    # key -> (value, expires_at)
        self.heap = []    # (expires_at, key), may hold stale entries

    def set(self, key, value, ttl, now):
        exp = now + ttl
        self.data[key] = (value, exp)
        heapq.heappush(self.heap, (exp, key))

    def expire(self, now):
        removed = 0
        while self.heap and self.heap[0][0] <= now:
            exp, key = heapq.heappop(self.heap)
            if key in self.data and self.data[key][1] == exp:   # still current?
                del self.data[key]; removed += 1
        return removed

c = TTLCache()
c.set("a", 1, ttl=10, now=0)
c.set("b", 2, ttl=5, now=0)
c.set("a", 3, ttl=20, now=1)              # refresh: (10, "a") is now stale
print(c.expire(now=6), sorted(c.data))    # 1 ['a']   b expired
print(c.expire(now=12), sorted(c.data))   # 0 ['a']   stale entry skipped

The price of lazy deletion is memory: the heap can hold more entries than there are live keys, one per refresh since the entry last surfaced. Redis takes a third route: it deletes an expired key when someone touches it, and in the background samples random keys that carry a TTL.

Recipes

Choose a structure for a leaderboard

Operations:  update a score (often), top 10 (often), a user's rank (sometimes)
Hash map:    update O(1), but top 10 means sorting on every query       ✗
Heap:        top 10 is cheap, but a user's rank is O(n)                 ✗
Skip list or balanced tree keyed by (score, user), with subtree counts:
             update O(log n), top 10 O(log n + 10), rank O(log n)       ✓
Plus a hash map user → score, so an update finds the old entry in O(1)

This combination is exactly a Redis sorted set: a skip list for order and ranks, plus a hash table for lookups by member.

Why building a heap is O(n)

Height from the bottom:   0      1      2      ...   h
Nodes at that height:     n/2    n/4    n/8    ...   1
Sift-down cost per node:  0      1      2      ...   h
Total work:  sum over k of (n / 2^(k+1)) × k  =  n × (1/4 + 2/8 + 3/16 + ...)  ≤  n

Most nodes sit near the bottom, where sifting down is cheap, so bottom-up heapify is linear even though n separate pushes would cost O(n log n).

Top-k from a stream of a billion items

Full sort:        O(n log n) time, O(n) memory     → all 1B items in memory    ✗
Min-heap of k:    O(n log k) time, O(k) memory     → k = 100, log k ≈ 7        ✓
Quickselect:      O(n) average, but needs every item in memory                 ✗
Heavy hitters:    a count-min sketch plus a small heap, in fixed memory

Keep the k largest seen so far in a min-heap; a new item replaces the root only when it beats the smallest of them.

Linked list, array or ring buffer for a queue?

Array with pop(0):    O(n) per dequeue → n dequeues cost O(n²)
Linked list:          O(1) per operation, but a pointer per node and poor locality
Ring buffer / deque:  O(1) per operation in contiguous memory → usually fastest

Equal big-O is not equal speed: at the same O(1), a contiguous ring buffer beats a linked list because the CPU cache does the rest.

When to use it, and when not

Use this table when picking a structure for a hot path, answering an interview question, or reviewing code that will see growing data. Find the operation you do most often, pick the structure that makes it cheap, then check the worst case of everything else you do.

Look beyond the table when:

  • n is small. For a few dozen items, a linear scan of an array often beats a hash map or a tree: no hashing, no pointer chasing, a cache line or two.
  • Data lives on disk or across a network. Count block reads and round trips instead; that is why databases use B+ trees and LSM trees rather than binary trees.
  • Many threads share it. Lock contention can dwarf the big-O, and concurrent structures trade some single-thread speed for scalability.
  • Exact answers are not required. Bloom filters, count-min sketches and HyperLogLog answer in fixed memory at the price of a bounded error.

Trade-offs and limits

StructureExtra memory beyond the elementsWhat it buys
Dynamic arrayspare capacity left after the last growthfastest scans, O(1) indexing
Linked listone or two pointers per node, plus an allocation eachO(1) splice at a node you hold
Hash tableempty slots to keep buckets short (Java’s HashMap resizes at a 0.75 load factor by default)O(1) average lookup
Balanced BSTtwo child pointers and balance data per nodeorder, ranges, O(log n) worst case
B-treenodes are only guaranteed half fullfew disk reads per lookup
Bloom filterabout 9.6 bits per item at a 1% false-positive ratemembership in tiny fixed memory; no deletes, no listing

Big-O is about time; memory is often what decides at scale. A structure that is O(1) but needs pointers per element can cost several times the raw data, which matters once the data no longer fits in RAM.

Common mistakes

  • Mutating a key after inserting it. A hash table files an entry under the key’s hash at insert time. Change a field the hash depends on and lookups miss the entry forever. Use immutable keys; Python refuses lists as dict keys for this reason.
  • Deleting from a Bloom filter. Clearing an item’s bits can clear bits other items share, creating false negatives. Use a counting Bloom filter or a cuckoo filter if you need deletes.
  • Sorting to answer a repeated query. Sorting on every top-k or median request costs O(n log n) each time. Maintain a size-k heap, or the two-heap median, as items arrive.
  • An adjacency matrix for a big sparse graph. A million nodes means 10¹² cells: 125 GB even at one bit each, for a graph that may have only a few million edges. Use adjacency lists.
  • Assuming size() is O(1). It usually is, but Java’s ConcurrentLinkedQueue.size() walks the whole queue, and its documentation says so. Calling it in a loop turns O(n) work into O(n²).

Check yourself

You need insert, delete-by-id and find-min, all in O(log n) or better. Which structure?

An indexed heap: a binary heap plus a hash map from id to heap position, so delete-by-id can sift from a known slot. A balanced BST keyed by (priority, id) with an id map also works and adds ordered iteration.

How big is a Bloom filter for 10 million items at a 1% false-positive rate, and how many hash functions should it use?

m = −n·ln p / (ln 2)² ≈ 9.6 bits × 10M ≈ 96M bits ≈ 12 MB, and k = (m/n)·ln 2 ≈ 6.6, so 7 hashes.

A B-tree with fan-out 256 indexes a billion keys. About how many levels does a lookup touch?

log₂₅₆(10⁹) ≈ 3.7, so 4 levels, and the top ones usually sit in memory. A binary tree would be about 30 levels deep.

Which common operation on Python’s collections.deque is O(n)?

Indexing in the middle, d[i]: the docs say indexed access is O(1) at both ends but slows to O(n) in the middle. Appends and pops at either end are O(1).

Questions about Data Structure Complexity Cheat Sheet

What is the time complexity of a hash table?

Insert, lookup and delete take O(1) time on average, because a good hash function spreads keys evenly and the table resizes to keep buckets short. The worst case is O(n), when many keys land in the same bucket through a poor hash function or deliberately crafted keys, which is why many languages randomize their hashing. Resizing costs O(n) occasionally, but amortized over all insertions it stays O(1) each. Java’s HashMap turns long buckets into balanced trees, which limits the worst case to O(log n) for comparable keys.

What does amortized time complexity mean?

Amortized complexity is the average cost per operation over a worst-case sequence of operations, rather than the cost of any single one. The classic example is appending to a dynamic array: most appends write into spare capacity in O(1), but when the array is full it allocates a larger block and copies everything in O(n). Because capacity grows geometrically, typically by 1.5 to 2 times, the copies are rare enough that n appends cost O(n) in total, or O(1) amortized each, even though one append can be slow.

When should I use a linked list instead of an array?

Rarely, in modern code. Linked lists win when you need O(1) insertion or removal in the middle of a sequence at a position you already hold a reference to, as in an LRU cache’s recency list, or when elements must never move in memory. For most other uses dynamic arrays are faster even when the big-O is equal or slightly worse, because their contiguous layout suits the CPU cache, while every list node is a separate allocation and a pointer chase. Default to arrays and deques, and measure before switching.