Skip to content
Tech Interview Prep
Technical interview guide

Arrays & Hashing

Contiguous storage, O(1) average-case lookups via hash maps, and the frequency-counting patterns they enable.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v7
Editorial status
Reviewed

Scope: Language-neutral, with operation costs cited from CPython 3.14, the C++ standard containers, and java.util as of Java 21.

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

append, doubling: O(1) amortised, O(n) for the one append that resizes\text{append, doubling: } O(1) \text{ amortised, } O(n) \text{ for the one append that resizes} fixed increment c over n appends: copies≈n22c,n=106, c=1000⇒5×108\text{fixed increment } c \text{ over } n \text{ appends: copies} \approx \frac{n^2}{2c}, \quad n=10^6,\ c=1000 \Rightarrow 5\times10^{8} chained table: expected probes O(1+α),α=nm\text{chained table: expected probes } O(1+\alpha), \quad \alpha = \frac{n}{m} doubling from 16 buckets, 1,000 inserts: rehashed entries=16+32+64+128+256+512=1008\text{doubling from 16 buckets, 1,000 inserts: rehashed entries} = 16+32+64+128+256+512 = 1008 ∑k=ij−1ak=Pj−Pi,Pj=∑k<jak\sum_{k=i}^{j-1} a_k = P_j - P_i, \quad P_j = \sum_{k<j} a_k hashing keys of length k:O(nk) time and O(nk) space\text{hashing keys of length } k: O(nk) \text{ time and } O(nk) \text{ space}

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.
yes, and equal no match key hash(key) bucket index stored key, same hash? return value miss: insert or absent

When to use and when not to

QuestionStructureCostDecides it because
Is x present, or is there a duplicate?setO(1) expected per element, O(n) spaceorder and counts are not needed
How many of each key?Counter / dictO(1) expected per updateone pass, no sort
Smallest key at or above x, or range sums on static datasorted list with bisect, or prefix sumsO(log n) per query, or O(1) after O(n) builda hash cannot answer order queries
Read by index, grow at the endlistO(1) read, amortised O(1) appendmid-sequence insert is O(n)
Constant-time delete with random pickarray plus index map, swap with lastO(1) expecteddeletion does not preserve order
Memory is the binding limitin-place sortO(n log n) time, O(1) extrano hash table allocation

Traps interviewers probe

  1. 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.
  2. 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}.
  3. 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.
  4. 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.
  5. 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.