Overview
Curated: · Written: · Reviewed:
Arrays & Hashing
In one line
Reach for an array when access is by position and writes happen at the end. Reach for a hash map or set when the question is membership, counting or grouping by key. Both give expected O(1) operations, and each buys that speed with memory, so state the memory cost with the time cost.
Key definitions
- Contiguous array: equal-width slots, so the address of element i is base + i × width. Indexing is O(1); inserting mid-sequence is O(n).
- Amortised O(1) append: geometric growth makes total copy work linear in n, but one append that triggers a resize is O(n).
- Load factor: entries divided by buckets. Implementations resize to keep it bounded.
- Hash and equality contract: equal keys must hash equal, and a stored key must not change its hash.
- Tombstone: a deletion marker in open addressing. It still lengthens probe sequences.
- Canonical key: a value that equivalent items share and non-equivalent items never share.
Formulas and complexity
How it works
- Lookup hashes the key, selects a bucket, then compares stored keys by equality until it finds a match or an empty slot.
- Insert performs the same walk and stores the entry. When the load factor passes its threshold, the table allocates more buckets and reinserts every entry.
- A key mutated after insertion sits under the hash it had when stored, so lookups for its new value search the wrong bucket.
When to use and when not to
| Question | Structure | Cost | Decides it because |
|---|---|---|---|
| Is x present, or is there a duplicate? | set | O(1) expected per element, O(n) space | order and counts are not needed |
| How many of each key? | Counter / dict | O(1) expected per update | one pass, no sort |
| Smallest key at or above x, or range sums on static data | sorted list with bisect, or prefix sums | O(log n) per query, or O(1) after O(n) build | a hash cannot answer order queries |
| Read by index, grow at the end | list | O(1) read, amortised O(1) append | mid-sequence insert is O(n) |
| Constant-time delete with random pick | array plus index map, swap with last | O(1) expected | deletion does not preserve order |
| Memory is the binding limit | in-place sort | O(n log n) time, O(1) extra | no hash table allocation |
Traps interviewers probe
- Two-sum that stores before querying pairs an element with itself. Two-sum on [3, 2, 4] with target 6 returns (0, 0). Fix: query first, then insert.
- Seeding the prefix counter with an empty dict drops every window that starts at index 0. On [2, -1, 2, 1, -2, 3] with k = 3 it returns 3, not 4. Fix: seed {0: 1}.
- Keys that change or are lossy. A key mutated after insertion leaves two entries in a dict, and get() finds the newer one. Joining segments with "-" maps ["a-b", "c"] and ["a", "b-c"] to one key, and sum(ord) maps "ad" and "bc" to one key. Fix: immutable tuples, and a key that is injective for the equivalence you need.
- Treating O(1) as unconditional for untrusted input. A fuzzer-built key set can make p99 jump from 40 µs to 12 ms at an unchanged load factor of 0.7. Fix: use the runtime's randomised or keyed hash, and measure the longest bucket.
- Forgetting tombstones. Linear probing with 700,000 live keys and 240,000 tombstones in 1,048,576 slots probes as if about 90% full. Fix: rehash to clear tombstones, and count them in the load factor.
Interview tips
Open with the query and both bounds: "A set answers membership in expected O(1) per element, so duplicate detection is O(n) time and O(n) space. Sorting is O(n log n) with O(1) extra space, and I'd choose it if memory is the constraint."
Expect these follow-ups:
- What happens under adversarial keys? Bounds become O(n) per lookup. Name the randomised hash as the defence.
- Why is one append slow? The resize copies every element once. Pre-size when the count is known.
- Why not a dict for range queries? A dict cannot answer the smallest key above x without a full scan.
- What is the memory multiplier? In CPython, a dict of 1,000 small integers measured about 4.6x the list holding the same values.
30-second outline: name the query, pick the structure, give expected and worst-case time with n and space, name the trap that applies (key contract, self-pairing, empty seed or tombstones), then state the edge case you would test first.
Feedback on this overview
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.