Core Data Structures and Complexity Trade-offs
Medium · Coding & Algorithms · Software Engineer · Onsite
Prompt
Walk through the internal mechanics and runtime trade-offs of four core container abstractions:
- Hash maps: Describe how arbitrary keys are mapped onto bucket indices, compare the two primary ways of handling key collisions (separate chaining and open addressing), define the load factor, and explain how dynamic table expansion works. Give both expected and worst-case Big-O bounds for lookup, insertion, and deletion.
- Dynamic arrays vs. linked lists: Compare contiguous memory buffers against node-and-pointer chains when reading an element by position versus inserting new elements.
- Stacks vs. queues: Contrast their ordering rules, give the Big-O cost of their fundamental operations, and describe practical engineering or algorithmic scenarios where each structure is the natural fit.
Scope & Expectations
- Hash table internals & asymptotic bounds: Clear account of key-to-slot indexing, chaining versus probing (including deletion handling), load-factor thresholds with amortized rehashing analysis, and when O(1) expected operations degrade to O(n).
- Contiguous vs. pointer-linked storage: Direct comparison of indexed address arithmetic, shifting versus pointer rewiring during insertions, and CPU cache behavior.
- LIFO vs. FIFO discipline: Accurate operation complexities paired with concrete applications that rely on last-in-first-out versus first-in-first-out ordering.
Step-by-step walkthrough
How a hash map turns a key into an array index
An array gives instant O(1) lookup when your keys are small integers
0, 1, ..., m - 1, because the computer jumps straight to sloti. A hash map (also called a hash table) brings that same speed to arbitrary keys—like strings"alice"or tuples(10, 20)—by combining an array ofmslots (called buckets) with a hash function that turns any key into an integer:bucket_index = hash(key) mod m (or hash(key) & (m - 1) when m is a power of 2)Two rules govern every hash map: - Hash-equality consistency: if two keys are equal (
a == b), they must produce the exact same hash (hash(a) == hash(b)). That is why mutable objects like Pythonlists cannot be keys: mutating a key after insertion changes its hash, stranding it in the wrong bucket. - Collisions are unavoidable: a collision happens when two different keys (a != b) land on the samebucket_index. By the pigeonhole principle (if you place more items than boxes, at least one box receives two or more items), collisions are guaranteed whenever possible keys outnumberm. Therefore, finding the bucket is only step one—the map must still compare stored keys with==to confirm an exact match.Let's trace a concrete numeric example with
m = 7buckets,hash(k) = k, and five keys[10, 22, 31, 4, 15]:10 mod 7 = 3 22 mod 7 = 1 31 mod 7 = 3 4 mod 7 = 4 15 mod 7 = 1Keys
10and31collide in bucket3, and keys22and15collide in bucket1. How the table stores colliding keys splits hash maps into two classic families.Collision strategy 1: separate chaining
In separate chaining, each bucket holds a small list (a "chain", typically a linked list or tiny dynamic array) of all
(key, value)pairs that hashed to that bucket:bucket 0: [] bucket 1: [(22, v2), (15, v5)] bucket 2: [] bucket 3: [(10, v1), (31, v3)] bucket 4: [(4, v4)] bucket 5: [] bucket 6: []- Search (
get): hash the key to pick one bucket, then scan that bucket's short list comparingk == key. - Insert (
put): scan the bucket's list; ifkeyis already there, overwrite its value; otherwise append(key, value). - Delete (
delete): find the matching pair in that bucket's list and remove it.
Separate chaining makes deletion effortless, handles
n > m(more items than buckets) without breaking, and degrades gradually as the table fills. Its trade-off is extra memory for list/node pointers and slower CPU cache behavior when chasing pointers across scattered heap nodes.class ChainedHashMap: """Minimal separate-chaining hash map that doubles buckets past load factor 0.75.""" def __init__(self, capacity: int = 8) -> None: self.buckets = [[] for _ in range(capacity)] self.size = 0 def _bucket(self, key): return self.buckets[hash(key) % len(self.buckets)] def get(self, key): for stored_key, stored_val in self._bucket(key): if stored_key == key: return stored_val raise KeyError(key) def put(self, key, value) -> None: bucket = self._bucket(key) for idx, (stored_key, _) in enumerate(bucket): if stored_key == key: bucket[idx] = (key, value) return bucket.append((key, value)) self.size += 1 if self.size > 0.75 * len(self.buckets): self._resize(2 * len(self.buckets)) def delete(self, key) -> None: bucket = self._bucket(key) for idx, (stored_key, _) in enumerate(bucket): if stored_key == key: bucket.pop(idx) self.size -= 1 return raise KeyError(key) def _resize(self, new_capacity: int) -> None: old_buckets = self.buckets self.buckets = [[] for _ in range(new_capacity)] for bucket in old_buckets: for stored_key, stored_val in bucket: self._bucket(stored_key).append((stored_key, stored_val))- Search (
Collision strategy 2: open addressing and tombstones
In open addressing, there are no outside lists at all: every
(key, value)pair sits directly inside one slot of the bucket array itself. When home sloti = hash(key) mod mis already occupied by another key, the table steps through a deterministic probe sequence until it finds either the target key or an empty slot_:- Linear probing: checks
i, i + 1, i + 2, ... (mod m). Neighboring slots sit right next to each other in RAM—giving great cache locality (one CPU memory fetch pulls several adjacent slots into fast cache)—but occupied slots clump into long contiguous runs called primary clustering (any key landing anywhere in a run makes that run even longer). - Quadratic probing: checks
i, i + 1, i + 4, i + 9, ... (mod m), i.e.(i + j²) mod mforj = 0, 1, 2, .... Jumping by squares breaks up primary clusters, leaving only milder secondary clustering (keys with the exact same initial slotifollow the same jumps). Whenmis an odd prime and the table is less than half full, quadratic probing is mathematically guaranteed to reach an empty slot. - Double hashing: checks
(i + j * h2(key)) mod m, where a second hash functionh2(key)(chosen non-zero and coprime tom) gives each key its own step size, eliminating both primary and secondary clustering.
Tracing our same five keys
[10, 22, 31, 4, 15]onm = 7with linear probing:insert 10 -> home 3 (free) slot: 0 1 2 3 4 5 6 insert 22 -> home 1 (free) [ _ , 22 , 15 , 10 , 31 , 4 , _ ] insert 31 -> home 3 busy -> slot 4 (free) insert 4 -> home 4 busy -> slot 5 (free) insert 15 -> home 1 busy -> slot 2 (free)Why deletion needs tombstones: look at keys
31(at slot4) and4(whose home is4, pushed to slot5). If you deleted31by resetting slot4to empty_, a later search for4would start at slot4, see_, and falsely conclude4is not in the map! Instead, deletion marks slot4with a special tombstone marker (DELETED): - Searches treatDELETEDas "keep probing" and stop only at4or a truly empty_. - Inserts (put) remember the firstDELETEDslot they pass, finish probing to make surekeydoes not already sit further along the run, and then reuse that savedDELETEDslot ifkeyis new. (Alternatively, linear probing can avoid tombstones by shifting subsequent entries backward.)- Linear probing: checks
Load factor, resizing, and amortized O(1) inserts
The load factor is
alpha = n / m, wherenis the number of stored entries andmis the number of buckets/slots. Under uniform hashing, Donald Knuth's classical formulas show how expected work grows withalpha:Metric Formula alpha=0.5 0.75 0.90 ----------------------------------- ---------------------------- --------- ----- ---- Separate chaining, miss (key comps) alpha 0.50 0.75 0.90 Separate chaining, hit (key comps) ~ 1 + alpha / 2 1.25 1.38 1.45 Linear probing, hit (slot probes) (1 + 1 / (1 - alpha)) / 2 1.50 2.50 5.50 Linear probing, miss (slot probes) (1 + 1 / (1 - alpha)^2) / 2 2.50 8.50 50.5Notice the contrast: chaining slows down gently (
alphacomparisons on a miss), whereas open addressing hits a steep wall asalphaapproaches1.0(50.5probes on a miss at90%full, and open addressing strictly requiresn < mso an empty slot still exists to stop misses). Consequently, real libraries resize beforealphagets high—Java'sHashMap(chaining) resizes above0.75, and CPython'sdict(open addressing) resizes above2/3(~0.67).How resizing stays O(1) amortized: when
alphacrosses the threshold, the map allocates a larger bucket array—typically 2x as many buckets—and rehashes (recomputeshash(key) mod new_mfor) every stored entry, sincehash mod 8andhash mod 16place keys in different buckets. One resize costs O(n), yet amortized time (the average cost per operation across a worst-case sequence of operations) remains O(1) because doubling happens exponentially rarely:Insert 1,024 keys starting from capacity 1 (doubling whenever full at 1, 2, 4, ..., 512): Total entries moved across all resizes = 1 + 2 + 4 + 8 + ... + 512 = 1,023 moves Average resize work per insert = 1,023 / 1,024 < 1 extra move per insert!If you instead grew capacity by a fixed
+100slots each time, resizes would move100 + 200 + 300 + ... + n = O(n²)entries total, degrading inserts to O(n) amortized!Hash map time complexities and worst-case defenses
Operation Average Case Worst Case When the Worst Case Happens --------- ---------------- ---------- --------------------------------------------------- Search O(1) O(n) All n keys collide into one chain or probe run Insert O(1) amortized O(n) Single resize step, or all n keys collide together Delete O(1) (amortized*) O(n) All n keys collide (*or table shrinks on low alpha)Average O(1) holds whenever two conditions are met: (1) the hash function distributes the workload's keys evenly across buckets, and (2) resizing keeps
alphabounded below a constant threshold so chains/probe runs have O(1) expected length.What triggers the O(n) worst case in production? Either a buggy hash function (like
hash(s) = len(s), dumping all 8-letter words into bucket 8) or an adversarial hash-flooding attack, where an attacker crafts thousands of HTTP form keys known to collide, turning n inserts into1 + 2 + ... + n = O(n²)CPU work. Production runtimes defend with two mechanisms: - Randomized hash salting: Python (PYTHONHASHSEED), Rust, and Go mix a secret per-process random seed into string hashes so attackers cannot predict which strings will collide. - Treeified buckets: Java 8+HashMapupgrades any single chain exceeding 8 nodes (when table capacity is at least 64) from a linked list into a balanced red-black tree, improving worst-case search/insert/delete from O(n) to O(log n) whenever keys are comparable.Arrays versus linked lists: random access, insertion, and CPU cache
An array stores elements side by side in one contiguous block of memory, whereas a linked list stores each element inside a separate heap node holding a pointer (
next, andprevin a doubly linked list) to its neighbor:Array in RAM (contiguous, item size = 8 bytes, base = 1000): addr: 1000 1008 1016 1024 [ 10 | 20 | 30 | 40 ] -> item i lives at 1000 + 8*i (1 arithmetic step!) Linked list in RAM (scattered heap nodes): head -> [10 | *-]---> [20 | *-]---> [30 | *-]---> [40 | None] addr 4080 addr 1120 addr 9300 addr 2560 (must hop pointer by pointer)Operation Dynamic Array Singly / Doubly Linked List -------------------------------------- -------------------- ------------------------------------ Random access (read/write index i) O(1) O(i) -> O(n) worst case Insert / delete at front (index 0) O(n) (shift n items) O(1) (rewire head pointer) Insert at back (append) O(1) amortized O(1) with a tail pointer (else O(n)) Insert / delete at known node pointer N/A (uses indices) O(1) after node (and before if doubly) Insert / delete at middle index i O(n) (shift n - i) O(i) to walk there + O(1) to rewire Extra memory per element 0 pointers (+slack) 1 or 2 pointer words per nodeWorked 1,000,000-element comparison: - Reading index
500,000in an array computesbase + 500,000 * sizein 1 step; in a linked list it follows 500,000 pointers one after another. - Inserting at index0in an array shifts all 1,000,000 elements one slot right (O(n)); in a linked list it allocates 1 node and updates 2 pointers (O(1)). - Even for middle insertions, hardware cache locality often favors arrays up to thousands of items: shifting contiguous bytes uses fast vectorized memory instructions, while each linked-list hop can stall the CPU on a RAM cache miss. Linked lists shine when another structure (like a hash map in an LRU cache) hands you the exact node reference so you can splice or unlink it in true O(1) without walking.Stacks versus queues: LIFO vs. FIFO, complexities, and use cases
Stacks and queues deliberately restrict which end you can touch so the data structure itself enforces processing order:
Stack (LIFO: Last-In, First-Out) Queue (FIFO: First-In, First-Out) push(30) pop() -> 30 enqueue(30) -> [30 | 20 | 10] -> dequeue() -> 10 | ^ back front [ 30 ] ---| (top) [ 20 ] [ 10 ]- Stack (LIFO — Last-In, First-Out):
- Complexities:
pushO(1) (amortized on a dynamic array, worst-case on a linked list),popO(1),peekO(1). - Typical use cases: the program call stack for function calls and recursion, editor Undo/Redo history, depth-first search (DFS) and backtracking, checking balanced parentheses/HTML tags, expression evaluation, and monotonic stacks (a stack kept sorted to find each item's next greater element in O(n)).
- Complexities:
- Queue (FIFO — First-In, First-Out):
- Complexities:
enqueue(back) O(1),dequeue(front) O(1),peek(front) O(1)—implemented via a circular buffer (an array whose front and back indices wrap around modulo capacity),collections.deque, or a linked list with bothheadandtailpointers. Callinglist.pop(0)on a plain array is O(n) because every remaining element shifts left! - Typical use cases: breadth-first search (BFS) for shortest paths in unweighted graphs, fair CPU/task/print scheduling, producer-consumer pipelines, and web-server request buffers.
- Complexities:
from collections import deque def brackets_balanced(text: str) -> bool: """Stack (LIFO): the most recently opened bracket must be closed first.""" matching_open = {")": "(", "]": "[", "}": "{"} stack = [] for ch in text: if ch in "([{": stack.append(ch) # O(1) amortized push elif ch in matching_open: if not stack or stack.pop() != matching_open[ch]: # O(1) pop return False return len(stack) == 0 def bfs_shortest_hops(graph: dict, start: str) -> dict: """Queue (FIFO): visits nodes strictly in order of hop count from start.""" distances = {start: 0} queue = deque([start]) while queue: node = queue.popleft() # O(1) dequeue from front for neighbor in graph[node]: if neighbor not in distances: distances[neighbor] = distances[node] + 1 queue.append(neighbor) # O(1) enqueue at back return distances assert brackets_balanced("([]{})") is True assert brackets_balanced("([)]") is False assert bfs_shortest_hops({"a": ["b", "c"], "b": ["d"], "c": ["d"], "d": []}, "a") == { "a": 0, "b": 1, "c": 1, "d": 2, }- Stack (LIFO — Last-In, First-Out):
Intuition & how it works
Think of organizing items in the real world:
- An array is a row of numbered apartment mailboxes (0, 1, 2, ...): you can walk straight to box #500 in one step, but squeezing a brand-new box #0 into the wall forces you to shift every single box one spot to the right.
- A linked list is a scavenger hunt of paper clues scattered around a building, where each note tells you where the next note is hidden: reaching clue #500 requires visiting 500 hiding spots in order, yet splicing a new note right after one you are already holding takes just rewriting two arrows.
- A hash map combines numbered mailboxes with a deterministic rule (a hash function) that turns any label—like "alice"—into a box number hash("alice") mod m, giving named lookups the near-instant speed of numbered boxes.
- A stack is a spring-loaded pile of cafeteria trays (LIFO, Last-In, First-Out: you always take the newest tray on top), while a queue is a checkout line (FIFO, First-In, First-Out: whoever arrived earliest is served first).
Without these specialized structures, naive choices bottleneck quickly. Storing (key, value) pairs in a plain unsorted list forces an O(n) linear scan on every lookup, inserting repeatedly at index 0 of an array copies all n items on every insert (O(n²) total), and jumping to index i of a linked list chases i scattered memory pointers instead of multiplying an offset in O(1).
Walk through a tiny concrete trace across all four structures:
1. Hash map (m = 4 buckets): suppose hash("cat") = 9 -> 9 mod 4 = 1, hash("dog") = 6 -> 6 mod 4 = 2, and hash("ant") = 5 -> 5 mod 4 = 1 (a collision in bucket 1). Under separate chaining, bucket 1 holds [("cat", 3), ("ant", 8)]; under open addressing (linear probing), "cat" takes slot 1 and "ant" steps to the next free slot (slot 3, since slot 2 holds "dog").
2. Array vs. linked list on [10, 20, 30]: reading index 2 (30) takes 1 address calculation (base + 2 * size) in the array versus 2 pointer hops from head in the list; prepending 5 at the front shifts 10, 20, 30 right (3 moves) in the array versus 1 pointer update (5.next = head) in the list.
3. Stack vs. queue on arrivals A, B, C: popping a stack returns C, B, A (reversing order, ideal for undo or matching nested brackets), whereas dequeuing a queue returns A, B, C (preserving arrival order, ideal for fair scheduling and breadth-first search).
Key points
- Hash map mechanics: computes
index = hash(key) mod m, requiresa == b => hash(a) == hash(b), and always verifies key matches with==because unequal keys can collide into the same bucket. - Separate chaining vs. open addressing: separate chaining stores a per-bucket list (effortless deletion, tolerates load factor
alpha = n / m > 1, extra pointer memory); open addressing stores entries inline inside the bucket array and probes via linear probing, quadratic probing, or double hashing (compact and CPU-cache-friendly, requiresalpha < 1and tombstones—special "deleted" markers—or back-shifting so deletions do not break later searches). - Load factor and resizing: keeping
alphabelow a constant threshold (0.75in JavaHashMap,~0.67in CPythondict) by doublingmand rehashing every key into its newhash(key) mod new_mbucket makesputamortized O(1) (at most< 2total moves per insert across arbitrary growth). - Hash map time complexities:
search,insert(amortized), anddeleteare all O(1) on average, and O(n) in the worst case when allnkeys collide (mitigated in practice by randomized hash seeds and Java 8+'s O(log n) red-black tree buckets). - Arrays vs. linked lists: arrays give O(1) random access and great cache locality (adjacent elements load together into fast CPU cache lines) but O(n) front/middle insertion due to shifting; linked lists give O(1) insertion/deletion given a direct pointer to the node, but O(n) random access and O(n) search to reach index
i. - Stacks vs. queues: both support O(1) push/pop (
stack, LIFO) and O(1) enqueue/dequeue (queue, FIFO via circular buffer /collections.dequeor head-and-tail linked list); stacks power call frames, DFS, undo, and syntax parsing, while queues power BFS, job queues, and streaming buffers.
Common mistakes
- Saying hash map operations are unconditionally O(1): always state O(1) average (amortized for insert) assuming uniform hashing and bounded load factor, and O(n) worst case on full collisions or during a single resize step.
- Copying buckets directly during a resize instead of rehashing: because
hash(key) mod mchanges whenmdoubles from8to16, every existing entry must be re-indexed into the new array. - Clearing an open-addressed slot to empty on
delete: wiping a slot breaks probe chains for keys inserted later along that cluster; you must leave a tombstone marker (or shift subsequent entries back under linear probing). - Mutating an object after using it as a hash-map key: changing fields used by
__hash__and__eq__makes the key's new hash point to a different bucket than where it is stored. - Claiming linked-list insertion is "always O(1)": rewiring pointers is O(1) only when you already hold a reference to that node (such as
head,tail, or a node looked up via a hash map); inserting at integer indexistill takes O(i) pointer hops to walk there. - Using Python
list.pop(0)orlist.insert(0, x)as a FIFO queue: removing from index0of a dynamic array shifts alln - 1remaining elements in O(n) time, turning an O(n) BFS into O(n²); always usecollections.deque.
Follow-up questions
- Why do hash table implementations often pick a power-of-two bucket count, and what risk comes with it? When
m = 2^k, the slow integer divisionhash % msimplifies to a single-cycle bitwise ANDhash & (m - 1). However,hash & (m - 1)inspects only the lowestkbits of the hash and ignores all upper bits—so keys whose low bits repeat (such as memory addresses aligned to multiples of 64 or multiples of1024) collide heavily unless the library first scrambles upper bits downward (for example, JavaHashMapcomputesh ^ (h >>> 16)before masking). - How can a hash map and a doubly linked list work together to implement an O(1) LRU cache? Store
(key -> node)in a hash map while linking all nodes in a doubly linked list ordered from most-recently used (head) to least-recently used (tail). Onget(key), the hash map jumps straight to the exact list node in O(1), and because a doubly linked list stores bothprevandnextpointers, you can unlink that node from the middle and move it toheadin O(1) without scanning; whenputexceeds capacity, you poptailin O(1) and deletetail.keyfrom the hash map. - How does CPython's dict maintain insertion order while still using open addressing for O(1) lookups? Since CPython 3.6 (and standardized in Python 3.7),
dictsplits storage into two arrays: a dense entries array that appends(hash, key, value)tuples sequentially in insertion order, and a sparse index table of small integers (0, 1, 2, ...) searched by open addressing that point into the dense array. Iterating over thedictsimply scans the compact dense array in insertion order with great cache locality, while key lookups probe the lightweight integer index table in O(1) average time.
Follow-up questions
- Why do hash table implementations often pick a power-of-two bucket count, and what risk comes with it?
- How can a hash map and a doubly linked list work together to implement an O(1) LRU cache?
- How does CPython's dict maintain insertion order while still using open addressing for O(1) lookups?
Similar questions
- Operating System and Networking Essentials
- Heavy-Ball Weighing and Bridge Crossing Puzzles
- Career Overview and Recent Project Deep Dive
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses