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.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain the contiguous-array cost model and how it changes a production decision.

Answer

The 90-second answer. An array is one contiguous allocation of equal-width slots. Element i sits at base + i × width, so indexing is one multiply-add and one load: O(1) regardless of n. Inserting or deleting at position i shifts every element after it, so those are O(n) in the number of elements moved. The production consequence is not the asymptotics, which everyone knows, but the layout: contiguous slots mean a scan touches every byte of every cache line it loads, and the hardware prefetcher runs ahead of it. That is why a flat array often beats a linked list or a hash map on a hot read path even when its big-O looks worse.

The mechanism, with numbers. On x86-64 a cache line is 64 bytes and a pointer is 8 bytes, so one line holds 8 pointers. Scanning a 1,000,000-element array of pointers touches 125,000 lines, and because the access is sequential the prefetcher hides most of the latency: the scan is bandwidth-bound, roughly 8 MB moved. A linked list of the same 1,000,000 elements touches one line per node, and those lines are scattered, so each hop is a dependent load that cannot be prefetched: on the order of 1,000,000 cache misses. At a typical ~80–100 ns DRAM latency against ~1 ns for L1, that is the difference between a few milliseconds and tens of milliseconds for the same logical traversal. (These are typical orders of magnitude, not a benchmark.)

Where it bites in production. The classic failure is a queue built on a Python list: q.pop(0) is O(n) because CPython memmoves the remaining pointers down. A 1,000,000-element list holds 8 MB of pointers; one front-pop moves ~8 MB, which at ~10 GB/s is ~0.8 ms. At 1,000 pops/s that is 0.8 core-seconds per second: a single core saturated by bookkeeping. Symptom: p99 latency climbs linearly with queue depth while p50 stays flat. Detection: a profiler (py-spy, perf) shows time in list_ass_slice/memmove rather than in your code, and allocation counters stay flat, which rules out GC. Fix: collections.deque, which is O(1) at both ends.

Same shape in Go: s = append(s[:i], s[i+1:]...) inside a loop is O(n²) and shows up as memmove in a CPU profile.

Choosing. Use an array when access is index-driven, iteration is the hot path, and mutation is at the end (append is amortised O(1) because CPython over-allocates). Reach for a deque for double-ended queues, a linked structure or an index-plus-free-list when you insert and delete in the middle and hold stable references, and a hash map when you need lookup by key rather than position. If a hot loop reads only one field of each record, split into parallel arrays (struct-of-arrays) so each cache line carries 8 useful values instead of 1.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

How do you map a 2D matrix to a 1D array using row-major vs. column-major indexing, and how does row-major layout affect CPU cache locality during traversal?

Answer

What a strong candidate says first

Both layouts are bijections from (r, c) to a flat offset in [0, R*C):

  • Row-major (C, C++, NumPy's default order='C'): k = r*C + c. Row 0 first, then row 1.
  • Column-major (Fortran, MATLAB, Julia, R, LAPACK/BLAS, Eigen's default): k = c*R + r. Column 0 first, then column 1.

Neither is more correct. The layout decides which loop order is fast: the index you vary in the innermost loop should be the one that advances by 1 in memory. In row-major that's c; in column-major it's r. Get that backwards and every access is a cache miss.

The trace

C
// C, row-major. a[r][c] is at r*C + c.
#define R 3
#define C 4
int a[R][C];

for (int r = 0; r < R; r++)
  for (int c = 0; c < C; c++)
    sum += a[r][c];   // offsets 0,1,2,3, 4,5,6,7, 8,9,10,11  - stride 1

for (int c = 0; c < C; c++)
  for (int r = 0; r < R; r++)
    sum += a[r][c];   // offsets 0,4,8, 1,5,9, 2,6,10, 3,7,11  - stride C

Cache arithmetic

x86-64 and most ARM cores fetch 64-byte lines (Apple M-series uses 128 B). With int64, one line holds 8 elements.

Take R = C = 4096, int64 -> 128 MiB matrix.

Traversal (row-major)StrideLines touchedLine bytes movedBytes used
row-by-row8 B2^21128 MiB100%
col-by-col32 KiB2^241 GiB12.5%

The column scan's live set is one line per row = 4096 x 64 B = 256 KiB. That fits a 512 KiB-2 MiB L2 (Ice Lake and later) but not a 256 KiB L2 (Skylake) or a 32-48 KiB L1, so the re-fetches come from L2/L3, not DRAM. The cost is L2/L3 latency (~14 / ~40+ cycles vs ~4-5 for L1) plus the extra L2->L1 traffic - a few x, not the 10-30x you'd see if the live set exceeded LLC. It also thrashes the TLB: 4096 rows x 32 KiB spans 128 MiB, i.e. 32768 4 KiB pages per column pass, far past the ~1500-entry L2 TLB.

Mitigations, in order of cost

  1. Loop interchange - swap the loops so the innermost index is stride-1. Free; compilers do it at -O2/-O3 when they can prove no aliasing (restrict in C helps).
  2. Blocking/tiling - process BxB tiles. A tile's live set is 8B^2 bytes; B = 64 fits 32 KiB L1, and each line is reused B times instead of once. This is what BLAS does internally.
  3. Transpose once - one O(RC) pass to match the hot loop. Worth it if the matrix is traversed many times, not for a single pass.
  4. Huge pages - 2 MiB pages cut the TLB footprint above by 512x.
  5. Choose the layout at allocation - if the algorithm is column-dominant, allocate column-major and let row-wise access be the slow one.

When column-major wins

  • You're calling LAPACK/BLAS, cuBLAS, or Eigen - they're column-major, and converting costs more than it saves.
  • The dominant access is column-wise: per-column reductions, column-wise normalization, feature-major ML data, Fortran/MATLAB/Julia/R interop.
  • The matrix is a batch of column vectors and you iterate vectors.
  • Symmetric case: in a column-major array, row-wise traversal with stride R is the bad pattern.

If the whole matrix fits in L1/L2, layout is irrelevant - everything is resident. The deciding rule is: match layout to the innermost loop's stride-1 direction; if you can't change either, tile; if you can't tile, transpose once.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Where does sets as membership structures matter, and where is it irrelevant?

Answer

A hash set earns its place when the question is exactly "have I seen this value before?" and you need the answer in expected O(1) per element. It is the wrong tool the moment the question is about order, multiplicity, ranges, or approximate membership, or when the domain is small and dense enough that a plain array or bitset beats hashing outright.

Where it matters

  • Deduplication and duplicate detection over a stream: one pass, O(n) time, O(n) memory.
  • Complement lookup (two-sum): for each x, test target - x in seen.
  • Graph traversal: a visited set turns BFS/DFS from O(V·E) into O(V+E).
  • Anti-joins and set difference in data pipelines.

Where it is irrelevant or wrong

  • Small n. For a handful of elements a list scan beats a set: hashing and table allocation cost more than a few pointer comparisons. The crossover is workload-dependent: measure it rather than assume.
  • Order matters → sorted list plus bisect, or a tree.
  • Counts matter → Counter / multiset; a set silently drops multiplicity.
  • Bounded dense integer domain → a bitset. A Python set of 10M ints costs on the order of hundreds of MB (each int object plus table slots); a bitset over the same range is 10,000,000 / 8 = 1.25 MB.
  • Approximate membership at scale → Bloom filter, trading false positives for a fraction of the memory.
  • Unhashable elements → set([[1, 2]]) raises TypeError; convert to a tuple or pick another structure.

Code

Python
def has_duplicate(a):
    seen = set()
    for x in a:
        if x in seen:
            return True
        seen.add(x)
    return False

Trace has_duplicate([3, 1, 3]):

  • x = 3: 3 in seen → False (seen is empty); seen.add(3) → {3}
  • x = 1: 1 in seen → False; seen.add(1) → {3, 1}
  • x = 3: 3 in seen → True; return True

One pass, O(n) time, O(n) memory. The naive alternative compares every pair: for n = 10,000 that is 10,000 × 9,999 / 2 = 49,995,000 comparisons.

Failure modes

  • Losing multiplicity: len(set(a)) < len(a) tells you a duplicate exists, not how many or which.
  • Relying on iteration order: Python set order is neither insertion order nor sorted; code that depends on it breaks across runs and versions.
  • Mutating an element after insertion: if its hash changes, the set can no longer find it.
  • Adversarial input: worst-case lookup degrades to O(n) under hash flooding. CPython randomizes str/bytes hashes by default (since 3.3), which mitigates this for built-ins but not for a custom __hash__.
QuestionStructure
"seen this exact value?"hash set
"how many times?"Counter / multiset
"in order, or in a range?"sorted list + bisect
"small dense domain?"bitset / boolean array
"probably seen it, low memory?"Bloom filter

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-4

What does the hash and equality contract guarantee, and what does it deliberately leave open?

Answer

The guarantee has two clauses. If a == b, then hash(a) == hash(b). And a key's hash must not change for as long as it is stored in the container. That is the whole contract. Everything else: how hashes are distributed, whether unequal objects collide, whether the hash is stable across processes, what the lookup costs: is deliberately left open.

Why those two clauses and nothing more. A hash container narrows to a bucket by hash, then confirms by equality. The first clause is what makes that narrowing sound: equal keys must land in the same bucket, or a lookup would probe the wrong place. The second clause is what keeps the entry findable: the bucket address was computed at insert time and is never recomputed.

Python
class Point:
    def __init__(self, x): self.x = x
    def __hash__(self): return hash(self.x)
    def __eq__(self, other): return self.x == other.x

p = Point(1)
seen = {p: "first"}   # hash(p) == hash(1) == 1, entry lands in bucket 1
p.x = 2               # hash(p) is now hash(2) == 2; the dict is untouched
print(p in seen)      # False - probes bucket 2, finds nothing
print(len(seen))      # 1 - the entry is still there, just unreachable

seen[Point(1)] raises KeyError for the same reason. Nothing raised at the mutation, because the mutation is invisible to the dict.

What is left open, concretely.

Left openConsequence
Unequal objects may share a hashCollisions are legal; only equal-with-different-hash is a bug
Hash distribution qualityNo uniformity requirement; a bad hash degrades to O(n) probes
Stability across processesPython randomizes str/bytes hashes per process (PYTHONHASHSEED); Java's String.hashCode is specified and stable. Persisting a Python hash is a bug
CostO(1) average is an implementation property, not a contract
Thread safetyThe contract says nothing; dict and HashMap are not safe for concurrent mutation
Iteration orderNot part of the contract for set/HashSet

Choosing a key. The deciding criterion is whether the fields that define equality can change while the object is stored.

Key choiceUse whenCost
Immutable value: tuple, frozen dataclass, Java recordFields are small, fixed, and equality is value-basedHash recomputed per lookup unless cached; large keys cost more
Surrogate ID: int primary key, UUIDNatural key is large, mutable, or must be stable across systemsExtra indirection to fetch the value; ID must be unique
Mutable object hashed on one stable fieldOnly the stable field participates in __eq__/__hash__; the rest is payloadAny change to the hashed field silently breaks lookups

A mutable key is acceptable in exactly one shape: the mutable state is not part of equality. An identity-keyed cache (keyed by id(obj) or a stable ID, with the payload mutating freely) is fine. So is a dict you rebuild after mutating keys. What is never fine is mutating a field that feeds __hash__ while the object is a key.

Failure modes and how to catch them.

  • Silent lost entry (the trace above). Detect with an assertion that key in d after any mutation, or a property test that mutates keys between insert and lookup.
  • Equal-but-different-hash duplicates. Two keys that compare equal land in different buckets, so the dict holds both and lookups find whichever bucket the probe reaches. Detect by building a dict from a list and asserting len(d) equals the number of distinct values.
  • Unhashable type. In Python 3, defining __eq__ without __hash__ sets __hash__ = None, so the class raises TypeError: unhashable type on first use. Cheap to catch in a unit test.
  • Hash flooding. Attacker-controlled keys with colliding hashes turn lookups into O(n) scans. Java 8+ treeifies a bin once it holds 8 entries and the table capacity is at least 64, giving O(log n) in that bin; Python randomizes str hashes per process to make collisions unpredictable.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Walk through the hash-table average versus worst case, including where engineers most often get it wrong.

Answer

The 60-second answer

Average case O(1) per lookup; worst case O(n) per lookup for a table holding n keys. Both are true, and the gap lives entirely in the assumptions attached to "average": a hash function that spreads the actual key set roughly uniformly, a bounded load factor, and keys nobody chose in order to slow you down. Remove any one and the constant-time claim is gone.

Insertion is amortized O(1), but a single insert that trips a resize is O(n): every key is rehashed into the new table. That is the half of the story people drop when they quote the average.

Mechanism, with numbers

A key is hashed to a bucket index; lookup cost is the length of the probe sequence or chain you land on. Nothing else in the structure matters.

Python
def bucket(k, m=8):
    return k % m          # stand-in for a hash function

table = [[] for _ in range(8)]
for k in (8, 16, 24, 32, 40):
    table[bucket(k)].append(k)

# table[0] == [8, 16, 24, 32, 40]
# table[1] .. table[7] == []

Lookup walks the chain from the head, so the comparison count is the key's position plus one: 8 costs 1, 16 costs 2, 24 costs 3, 32 costs 4, 40 costs 5. Average over these five keys: 3 comparisons, on a table that is 62% empty. Spread the same five keys across the eight buckets instead and the load factor is α = 5/8 = 0.625, giving an expected successful-search cost of about 1 + α/2 ≈ 1.3 comparisons. Same table, same keys, 2.3× the work: the hash decided it, not the implementation.

Where engineers get it wrong

  1. Quoting O(1) unconditionally. It is a statement about a distribution, not about the data structure. If you cannot say what makes the distribution uniform, you have not answered the question.
  2. Assuming the worst case requires an attacker. It does not. std::unordered_map<int, int> in libstdc++ hashes integers to themselves, so keys 0, 8, 16, 24… all collide in a table of 8 buckets with no adversary present. Sequential IDs, timestamps truncated to a power of two, and low-cardinality enums do this by accident.
  3. Forgetting that resize is O(n). A single put can rehash the whole table. That is a p99 spike, not an average, and it is why a service can look healthy at p50 and time out at p99.
  4. Treating the hash as opaque. String.hashCode() in Java is specified in the Javadoc: deterministic and computable by anyone holding your keys. The 2011 hashDoS disclosures (Klink and Wälde, 28C3) took down PHP, Java, ASP.NET, Ruby and Python services with a few thousand crafted request parameters.
  5. Assuming every runtime has the same worst case. Java 8+ converts a bin to a red-black tree at 8 entries and back to a list at 6, so a single bin's lookup is O(log k) rather than O(k). Python randomises str/bytes hashing per process (PYTHONHASHSEED) and has used SipHash-1-3 since 3.4. Go seeds each map with a random hash0. Rust's default HashMap uses SipHash with per-process random keys. C++'s std::unordered_map does none of this by default.

What to do about it

For untrusted keys, use a keyed or randomised hash: the platform default where one exists, a wrapper type with your own keyed hash where it does not. Keep the load factor bounded: Java's HashMap defaults to 0.75 and doubles at that point; Go grows a map once buckets average 6.5 entries; CPython resizes a dict at two-thirds full.

Detection is measurable: track the longest chain or probe length, not just the load factor, and alert on it. When a lookup-heavy service shows unexplained tail latency, the longest bucket is the first thing to plot: a flat p50 with a rising p99 is the signature of a degenerate hash, and it will not show up in a throughput test that uses sequential integer keys.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

Walk me through what happens inside a hash table when two keys collide: chaining vs open addressing, what the load factor controls, when and why the table resizes, and what the worst-case lookup cost is and how a good hash function avoids it.

Answer

A collision is two distinct keys whose hashes map to the same slot, and the table keeps both reachable either by hanging a list off that slot (chaining) or by probing onward through neighbouring slots (open addressing). Load factor, resizing and the O(n) tail all follow from which one you picked and how full the table is.

Mechanically: m slots, n entries, α = n/m. With chaining a lookup hashes to the bucket and then walks that bucket's list comparing with equals: one hash, then one comparison per entry in the bucket, so with a good hash the expected chain length is α and lookup costs about 1 + α/2 comparisons when successful and 1 + α when not. With open addressing the entries live in the array itself: a key whose home slot is taken probes onward (linear, quadratic, or double hashing) until it finds the key or an empty slot. Cost is the probe count, and clusters of occupied slots merge as the table fills:

αchaining, unsuccessful (≈ 1+α)linear probing, unsuccessful ½(1 + 1/(1−α)²)
0.51.52.5
0.751.758.5
0.91.950.5

Those are the classic linear-probing estimates: at α = 0.9 an unsuccessful lookup touches about 50 slots on average where chaining touches 2, which is why open-addressing tables resize at 0.5–0.75 and chaining tables tolerate more.

Resizing fires when α crosses the threshold. The table allocates roughly twice the capacity and re-inserts every live entry, because the bucket index is a function of m: home slots change, so nothing can be copied in place. One resize is Θ(n) copies and shows up as a latency spike. The amortisation comes from doubling: filling a million entries from empty moves 32 + 64 + … + 1,048,576 entries across resizes, under 2.1 million moves total, about two per inserted key. java.util.HashMap (Java 21) resizes at a default load factor of 0.75; Python's dict is documented as O(1) average, O(n) worst case.

Deletion is the asymmetry people skip. Chaining unlinks a node. Open addressing cannot leave a hole without breaking every probe sequence that passed through it, so it leaves a tombstone or shifts entries backward; delete-heavy churn with no compaction keeps probe counts at their old level while n falls.

Worst case is O(n) either way: every key in one bucket, or every key in one probe run. It happens when the hash is poor: a hashCode() that returns a constant, or that mixes only a low-cardinality field like a status code, so eight buckets carry a million entries, or predictable: an adversary who can choose keys manufactures collisions and turns the request path into a linear scan, which is why Python salts the str and bytes hash per process and why Java's HashMap promotes a bucket to a red-black tree at 8 entries (with a table of at least 64 slots), capping lookup at O(log n) for comparable keys. A good hash spreads keys uniformly so bucket occupancy stays near α and probes stay O(1) expected. It cannot bound a worst case it did not choose: that is what "average O(1)" means, and it is why the O(n) number belongs in the design doc next to the map.

In practice: chaining for large entries, cheap deletion, and tolerance of α near 1; open addressing when the table is small and cache-resident and you can pay to resize at 0.5–0.75. On a latency-sensitive path, watch per-bucket occupancy or probe counts: p99 lookup rising while entry count is flat is the hash degrading, not the load growing.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

A teammate proposes a design that hinges on chaining versus open addressing. How do you evaluate it?

Answer

What I'd say first

Ask three things before arguing: what load factor the design actually runs at, whether anything deletes, and whether anything holds a pointer to an entry across inserts. Then: both are O(1) average, so the choice is decided by memory layout, deletion semantics and pointer stability, not by big-O. Default to the platform's map unless a profile says the map is hot.

Mechanism

Open addressing keeps every entry in one array. A lookup probes a sequence of slots (linear, quadratic, or double hashing) until it finds the key or an empty slot. Entries are contiguous, so a lookup usually touches one or two cache lines. The cost is that probe length is a nonlinear function of load factor α. Knuth's classic results for linear probing under uniform hashing:

αavg probes, hitavg probes, miss
0.51.52.5
0.752.58.5
0.95.550.5

(hit = ½(1 + 1/(1−α)), miss = ½(1 + 1/(1−α)²).)

At α = 0.9 a miss costs ~50 probes; at 0.5 it costs 2.5. That is why every real open-addressing table resizes well before full: CPython's dict grows when the table is 2/3 full, and Java's HashMap, which chains, defaults to a 0.75 load factor.

Deletion is the second difference. Removing from a chain is a list unlink. Removing from an open-addressed table cannot leave an empty slot, or later probes stop early and miss keys behind it; you leave a tombstone. CPython marks it DKIX_DUMMY. Tombstones count as occupied for probe purposes, so a table that has seen heavy churn probes like a full one until a resize rebuilds it.

Worked arithmetic

1M entries, 8-byte keys, 8-byte values, 64-bit pointers.

  • Open addressing: 2^21 = 2,097,152 slots × 16 B = 32 MiB, α ≈ 0.48.
  • Chaining: 2^20 = 1,048,576 bucket pointers × 8 B = 8 MiB, plus 1M nodes × 24 B (key, value, next) = 24 MiB → 32 MiB, α ≈ 0.95.

Same memory, same asymptotic cost. The difference is that the open-addressed lookup touches one array, while the chained lookup touches the bucket array and then a node that malloc placed somewhere else. On a server CPU where an L1 hit is ~4 cycles and a DRAM miss is ~200 cycles, that second miss dominates the lookup. (Illustrative figures: measure on your hardware.)

Failure modes

  • Open addressing + tombstones + no periodic rebuild: probe length climbs toward the miss column above and never recovers. Detect with a probe-count histogram or by tracking tombstone fraction.
  • Chaining + adversarial keys: every key lands in one bucket and lookups become O(n). Java's HashMap treeifies a bin at 8 entries and untreeifies at 6 to bound this: the fix for the 2011 hashDoS class of attacks. Open addressing has no equivalent; it just clusters.
  • Open addressing + resize: rehashing moves every entry, so any pointer or index you handed out is invalidated. If callers hold references into the table, chaining's stable nodes are the safer choice.
  • Chaining + large keys: each node carries the key plus a pointer, so per-entry overhead is higher; open addressing wins on memory when entries are small.

What I'd actually do

Take the platform default (Python dict, Java HashMap, Go map) unless the profile says the map is hot. If it is, benchmark with the real key distribution and the real load factor: a synthetic uniform-key benchmark hides exactly the clustering a skewed distribution produces. And check the deletion pattern: a workload that inserts and deletes heavily is the one where tombstones bite.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

How does dynamic resizing and rehashing work in a hash map, and how does load factor tuning balance lookup latency against memory overhead?

Answer

Dynamic resizing allocates a larger backing bucket array (typically $2\times$ the prior capacity) and recomputes the bucket index for every existing entry. Because bucket assignments depend on the capacity: traditionally $index = hash(key) \pmod M$, or $hash(key) & (M - 1)$ when $M = 2^k$: an entry cannot stay in its old slot index. Rehashing takes $O(N)$ time, where $N$ is the number of active entries, yielding an amortized $O(1)$ insertion cost.

The load factor $\alpha = N / M$ (active elements divided by bucket count) determines the threshold for resizing. Tuning $\alpha$ balances memory bloat against probe sequence length or collision chain length.

Chaining vs. Open Addressing

MechanismTypical Default $\alpha$Cost Model at $\alpha$Consequence of Increasing $\alpha$
Separate Chaining (e.g., java.util.HashMap)$0.75$Expected search time: $1 + \alpha / 2$Memory is compact, but linked traversals induce cache misses when chains deepen.
Open Addressing (Linear Probing, e.g., Python dict)$0.66$ to $0.75$Expected successful search: $\approx \frac{1}{2}(1 + \frac{1}{1 - \alpha})$High sensitivity: as $\alpha \to 1$, primary clustering collapses probe performance toward $O(N)$.

Worked Rehash Index Arithmetic

When a table doubles from $M = 8$ ($2^3$) to $M' = 16$ ($2^4$), the mask extends from binary 0111 to 1111. An element's new bucket index is determined solely by whether the newly unmasked bit in the hash code is $0$ or $1$:

Hash code:   ...0001 0101 (21)
Old M = 8:   21 & 0b0111  = 5
New M = 16:  21 & 0b1111  = 5    (4th bit is 0 -> index unchanged)

Hash code:   ...0001 1101 (29)
Old M = 8:   29 & 0b0111  = 5
New M = 16:  29 & 0b1111  = 13   (4th bit is 1 -> old_index + old_M = 5 + 8 = 13)

The Operational Trade-Off and Failure Modes

Setting $\alpha = 0.5$ cuts collision frequency and tightens latency distributions: lookups encounter fewer memory dereferences, but $50%$ or more of bucket pointers or slots sit empty. Conversely, raising $\alpha = 0.9$ saves table memory by keeping slot utilization high, but raises p99 and p99.9 lookup tail latencies significantly due to extended collision resolution.

In latency-sensitive real-time systems, the primary failure mode is resize-induced tail latency spikes. Reallocating and copying millions of entries in a single thread can freeze request handling for tens to hundreds of milliseconds. Mitigations include:

  1. Pre-sizing: Setting initial capacity via constructor arguments when input cardinality is known (e.g., new HashMap<>(expectedSize / 0.75f + 1) in Java).
  2. Incremental Rehashing: Allocating the new array alongside the old one and migrating a small batch of buckets on each subsequent read or write (as implemented in Redis), avoiding the monolithic stop-the-world rehash pause.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Describe load factor and resizing and the evidence you would collect before relying on it.

Answer

What a strong candidate says first. Load factor α is entries ÷ buckets. It is the one number that predicts lookup cost: with linear probing, a successful search averages about ½(1 + 1/(1−α)) probes and an unsuccessful one about ½(1 + 1/(1−α)²). At α = 0.5 that is 1.5 and 2.5 probes; at α = 0.9 it is 5.5 and 50.5. That curve is what forces resizing. Implementations cap α: CPython's dict resizes at two-thirds full, Java's HashMap defaults to 0.75, Go's map grows past 6.5 entries per 8-slot bucket, and when the cap is crossed they allocate a larger table and rehash every entry: O(n) work amortised to O(1) per insertion.

Worked trace (Java HashMap, JDK 17 defaults). Capacity 16, load factor 0.75, so threshold = 16 × 0.75 = 12. Puts 1–12 fill the table with no resize. The 13th put sees size 13 > 12, doubles the table to 32, and rehashes all 13 entries; the new threshold is 24. The 25th put doubles again to 64, threshold 48. A bulk load of n entries therefore pays about log₂(n/16) rehashes, and the last one moves n/2 entries inside a single put.

How the three mainstream maps differ.

Collision handlingResize triggerUser control
CPython dictopen addressing, perturbed probing2/3 fullnone
Java HashMapchaining; bins treeify at 8 entries, untreeify at 60.75 by defaultconstructor sets initial capacity and load factor
Go map8-slot buckets with overflow chainsload factor 6.5initial capacity hint only

Evidence to collect before relying on it.

  • Memory profile at the target cardinality, not at 100 entries: tracemalloc snapshots in Python, pprof heap in Go, jmap -histo or JOL in Java. Compare container bytes against a packed-array baseline; a dict or map typically runs 3–4× the array.
  • Probe or chain-length instrumentation. For open addressing, count probes per lookup; for chaining, histogram bucket lengths. Java's HashMap exposes neither, so subclass it or use a custom map; Go's runtime exposes neither, so fall back to the lookup latency distribution.
  • A resize trace: sample capacity (or sys.getsizeof) across a bulk load and correlate the steps with latency spikes. The p99.9 during a load that crosses a resize boundary is the number that matters, not the mean.
  • An adversarial key set: keys with identical hashes (Java's "Aa" and "BB" collide) to measure worst-case lookup. Load factor says nothing about this; only the key distribution does.

Trade-offs. Pre-sizing (new HashMap<>(n), make(map[K]V, n), dict.fromkeys) buys a flat latency profile and costs the memory up front. It is right when the cardinality bound is known and the path is latency-sensitive. It is wrong when keys are attacker-controlled or the bound is a guess: sizing to attacker input is a memory DoS, and a guessed bound is paid for the whole run. Raising the load factor trades memory for probe time, and only Java lets you set it.

Failure modes. Collision flooding drives one bucket to O(n) lookups: detect it with the chain-length histogram or p99 lookup latency, not the mean. A resize spike appears as a single slow put; detect it by correlating latency with capacity changes. Memory blowup shows up only in the heap profile, because the happy path hides it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

What trade-off does hashing for constant-time deletion force that a junior answer usually skips?

Answer

The 90-second answer

Constant-time deletion costs you order. A hash map plus a backing array gives expected O(1) insert, delete and uniform random pick, but only if deletion swaps the target with the last element. That swap is what makes the array's order arbitrary, so iteration order becomes unspecified. That is a semantic change, not a performance one. A junior answer stops at "swap with the last element and fix the index"; the part it skips is that you have now promised callers nothing about the sequence they get back, and anything downstream that assumed insertion order, sorted order, or a stable cursor is now wrong.

Mechanism

The array holds the elements; the map holds each element's current index. Deletion reads the victim's index from the map, pops the tail, and if the victim was not the tail, writes the tail into the hole and updates the tail's recorded index.

Python
class RandomSet:
    def __init__(self):
        self.items, self.index = [], {}
    def add(self, v):
        if v in self.index:
            return
        self.index[v] = len(self.items)
        self.items.append(v)
    def remove(self, v):
        i = self.index.pop(v)
        last = self.items.pop()
        if i < len(self.items):      # victim was not the tail
            self.items[i] = last
            self.index[last] = i

Trace

add(10), add(20), add(30) → items = [10, 20, 30], index = {10: 0, 20: 1, 30: 2}.

remove(10): i = index.pop(10) = 0; last = items.pop() = 30, so items = [10, 20]; len(items) = 2 and 0 < 2, so items[0] = 30 → items = [30, 20], index[30] = 0. Final index = {20: 1, 30: 0}.

Iterating now yields 30, 20. The element inserted last is first. That reordering is the trade-off, visible in four lines.

What the hash forces on you

  • Hashable, stable keys. Elements must hash and compare consistently. A mutable object whose hash changes after insertion strands its entry in the map and the array disagrees with it.
  • Two structures, roughly double the pointer memory: the array plus the map, both holding references to the same objects.
  • No stable handles. Any external cursor or index into the array is invalidated by a swap. If callers hold positions, they must hold values and re-look-up.
  • Duplicate policy is yours. The map keys on value, so add above silently dedupes; a multiset needs counts.

When not to use it

If order matters, this structure is the wrong tool. A sorted array gives O(log n) insert/delete and keeps order; a balanced tree or ordered map gives O(log n) with stable iteration. You cannot have O(1) delete and preserved order with an array: pick which one the caller actually needs.

NeedStructureDeleteOrder
O(1) delete, order irrelevantarray + position mapO(1) expectedunspecified
Order preserved, delete raresorted arrayO(n) shiftsorted
Order preserved, delete commonbalanced tree / ordered mapO(log n)sorted

Failure modes

A caller that iterates and compares against an expected sequence passes on the happy path and fails intermittently once a delete lands mid-array: the test is order-sensitive but the structure never promised order. The fix is to document iteration order as unspecified at the API boundary, or to sort before returning if the caller genuinely needs a sequence. The second failure is a stale index: code that cached index[v] and reuses it after an unrelated delete reads the wrong slot, because the swap moved a different element into that position.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

What failure would you inject to check a team's understanding of insertion-ordered maps?

Answer

The 90-second answer

Inject a reordering failure, not a crash: replay the team's own test input under a different hash seed, a different table size, or a different runtime, and assert the same thing. If the suite asserts on list(m) where only set membership is guaranteed, it flips from green to red with no code change. The check is whether the team can name which container promises order and which merely happens to produce it on this machine.

Two traps make this worth injecting. First, == on a Python dict ignores order, {"a": 1, "b": 2} == {"b": 2, "a": 1} is True, so a test that looks like it checks ordering does not. Second, order in a hash container is a function of the hash and the table size, so it moves when the load factor, the seed, or the version moves.

Mechanism

Insertion order survives only when the implementation keeps an auxiliary structure: a linked list (LinkedHashMap), a compact insertion-ordered entries array (CPython's dict), or an index (IndexMap). Otherwise iteration walks buckets, and the bucket index is derived from hash(key) and the current capacity. Anything that changes capacity or the hash changes the walk.

ContainerOrder
Python 3.7+ dictinsertion order, language guarantee
Python setnone; hash-randomized per process
Java HashMapnone; bucket order, changes on resize
Java LinkedHashMapinsertion order, or access order if constructed with accessOrder=true
Go mapnone; runtime randomizes each range
JS Mapinsertion order
JS objectinteger-like keys ascending first, then string keys in insertion order
Rust HashMapnone; IndexMap for insertion order

The injection, per runtime

Python: same test, two seeds:

Shell
PYTHONHASHSEED=0 pytest tests/test_order.py
PYTHONHASHSEED=1 pytest tests/test_order.py

Hash randomization is on by default since 3.3, so a set literal can iterate differently in each process. A test that passes under one seed and fails under the other was asserting on an accident.

Go: range over a map is randomized per iteration, so a single run proves nothing:

Shell
go test -count=100 ./...

Java: HashMap's default table is 16 buckets with a 0.75 load factor, so the 13th entry triggers a resize to 32 and can reorder iteration. Add one key to the fixture and watch a passing test fail.

Failure modes and detection

The bug is a test that passes locally and fails in CI on a different runtime, or an API that serializes a map and a client that depends on key order. It hides because the happy path uses a key set small enough to fit one table size. Detect it by running the suite under multiple seeds and -count=N, and by grepping for assertions on list(...), str(...), or repr(...) of unordered containers.

What to do instead

Assert on set(result) when order is irrelevant, and on list(result) only where the contract promises it. When order is part of the answer, use a container that promises it (LinkedHashMap, IndexMap, OrderedDict) and remember OrderedDict compares order-sensitively while dict does not.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

You insert an object into a HashMap and then mutate one of the fields the hash was computed from. What breaks, what does it look like at runtime, and how do the language runtimes you use defend against it?

Answer

The assumption I'd name first: a key is treated as immutable for as long as it lives in the map. In Java's HashMap and Python's dict alike. Break that assumption and the map routes by a value that has since changed. put picks a bucket from the key's hash at insert time; get picks a bucket from the key's hash at probe time. If the two hashes disagree, the probe lands elsewhere and misses, even though the entry is sitting in the table holding its value. Neither runtime throws; both are silent.

Mechanically, the entry went into the bucket chosen by hash(k); get(k') recomputes the hash from the mutated object and probes a bucket selected by a different number. equals is only consulted inside the candidate bucket, so the old entry never gets compared: the miss happens before equality is ever involved. That's the boundary with the hash-and-equality contract entry: your hashCode/equals (or __hash__/__eq__) can still be perfectly consistent; what you broke is the key's lifecycle. Naming the mechanism is what separates "the map is broken" from a diagnosis, and it points the fix at the key rather than the container.

Java
// Java 21
final class Tag {
    String name;                        // mutable field feeding hashCode
    Tag(String n) { name = n; }
    @Override public int hashCode() { return name.hashCode(); }
    @Override public boolean equals(Object o) {
        return o instanceof Tag t && t.name.equals(name);
    }
}

Map<Tag, String> m = new HashMap<>();
Tag t = new Tag("alpha");
m.put(t, "v");
System.out.println(m.size());           // 1
t.name = "beta";                        // hash changed under the map
System.out.println(m.get(t));           // null  <- "I just put this in"
System.out.println(m.containsKey(t));   // false
System.out.println(m.remove(t));        // null  <- ghost: entry is still there
System.out.println(m.size());           // 1

The debugging shape is the one that burns an afternoon: get returns null for an object you just put in. size() says 1. containsKey on the very same reference says false. remove returns null and the count does not move: the entry is now a ghost, still reachable by iteration and still holding whatever the value references.

SymptomWhat it means
get(t) null, size() 1probe used the new hash, missed the old bucket
remove(t) null, size() unchangedghost entry; leaks until clear/resize
two entries where a.equals(b)a second put inserted beside the first

That last row is the second-order damage: after mutating, put an equal key again and the map now holds two entries that are equal to each other, so size, containsKey and iteration disagree. The one-key-one-value invariant is broken with no exception. Java's fail-fast iterators only fire on structural modification, and changing a field is not one, so nothing warns you.

It survives casual testing because fixtures insert a key and never touch it again. It is also quietly load-dependent: the bucket index is the spread hash taken modulo table capacity, so if the mutated hash differs from the original by a multiple of the capacity, both probes land in the same bucket and the lookup keeps working. A 16-slot test map and a 65,536-slot production map can disagree about whether the code is correct.

Fixes, in the order I'd reach for them: immutable key types. String, boxed primitives, records whose components are themselves immutable (a record with a List field is final but its hash follows the list; Object[]/array.hashCode() is identity-based in Java, another trap); or derive the key from stable identity (id, UUID, primary key) and put the mutable object in the value. If you truly must mutate, remove/mutate/reinsert under the same lock works, but that is discipline across every call site, not a guarantee.

On runtime defences, be precise that they attack different failures. Python makes opting in explicit: a class that defines __eq__ without __hash__ gets __hash__ = None, so it raises TypeError: unhashable type and never becomes a key by accident. Python salts str/bytes hashes per process (PYTHONHASHSEED, on by default) so collision-DoS attempts and iteration order don't reproduce across runs: irrelevant to mutation. Per-bucket collision handling, chaining or probing, keeps genuinely colliding keys distinct by comparing equals inside the bucket; it defends against collisions, not against a key that moved. JavaScript Map is the interesting contrast: object keys compare by identity (SameValueZero), so mutating the object does not break lookup at all, though a key built as a string from mutable fields reintroduces exactly this bug. None of these defend against mutation. Key immutability is the only thing that does.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Teach frequency counting to an engineer who has only seen it as a rule of thumb.

Answer

Frequency counting is one pass over the input maintaining a map from key to integer count. You reach for it whenever the question is "how many of each" or "do these two hold the same multiset": anagram checks, grouping, top-k, majority element, first non-repeating character.

State the assumptions before you commit: keys are hashable, the hash spreads them, and you can afford memory proportional to the number of distinct keys. If any of those fails, the linear bound is gone.

Why it is linear. Each element is hashed to a bucket in expected O(1) and the counter there is incremented. The map grows by doubling and rehashing every key when it fills, but that cost is amortized across the inserts that triggered it, so the total stays O(n) expected. The word "expected" is doing real work: it assumes the hash distributes keys evenly. Worst case every key collides into one bucket, each insert scans a chain, and you get O(n) per insert, O(n²) total.

Python
from collections import Counter
import heapq

Counter("listen") == Counter("silent")          # True, O(n) expected

counts = Counter("abracadabra")                 # {'a':5,'b':2,'r':2,'c':1,'d':1}
heapq.nlargest(2, counts, key=counts.get)       # ['a','b'] or ['a','r'] — the tie at 2 is arbitrary

Trace of Counter("abracadabra"): a→1, b→1, r→1, a→2, c→1, a→3, d→1, a→4, b→2, r→2, a→5. Result {'a':5,'b':2,'r':2,'c':1,'d':1}. nlargest(2) returns 'a' (5) plus whichever of 'b'/'r' the heap surfaces first; if the tie matters, sort with an explicit key instead.

Arithmetic at n = 1,000,000 characters: counting is 1M hash-and-increment steps. Sorting is ~n·log₂n ≈ 20M comparisons, each a string compare. Counting wins by roughly 20×, and the gap widens with n.

Trade-offs. Sorting hands you order for free; counting throws it away. If you need sorted output, sort once at the end: O(d log d) over d distinct keys, not O(n log n) over all elements. For the top k, a heap over distinct keys is O(d log k), better than sorting all d when k ≪ d. If keys are small integers in a known range, a plain array beats the map: no hashing, no collisions, O(range) memory.

Failure modes.

  • Adversarial or clustered keys. If an attacker controls the keys they can force collisions and degrade you to O(n²). Java's HashMap treeifies a bucket after 8 entries to bound this; Python randomizes string hashes per process. Detection: instrument per-bucket chain length, or benchmark with hostile input.
  • Memory blowup from high cardinality. Counting 10⁹ events with 10⁹ distinct keys holds 10⁹ entries: gigabytes. Detection: track distinct-key count and process RSS; if cardinality is unbounded, switch to approximate counting (a Count-Min sketch) or an external sort.
  • Hashing long keys. Hashing a string is O(len), so counting n strings of length L is O(n·L), not O(n). Detection: it appears as a constant-factor slowdown on long keys, not a complexity change.

The decision rule: count when you need multiplicity and not order, sort when you need order, heap when you need only the extremes.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

If last week's incident involved the complement lookup pattern, what would you write in the report?

Answer

A strong candidate opens with the two lines that decide the report, what broke and what it cost, then gives the timeline, the root cause with the failing input, and the fix. Everything else is appendix.

Summary. The pair matcher returned index pairs drawn from more than one request. A refactor hoisted the complement map out of per-call scope so it could be reused, and stale entries from earlier batches satisfied later lookups.

Impact. Between deploy 14:02 and rollback 14:42 UTC the matcher emitted 1,180 pairs; 37 of them mixed entries from different batches, and 12 of those reached the payout path. (Figures illustrative.) No data loss; the bad payouts were reversed.

Timeline (UTC). 13:58 deploy matcher@2.4.0. 14:02 first cross-batch pair logged. 14:19 payout reconciliation flagged a mismatch. 14:31 on-call confirmed the matcher as source. 14:42 rollback. 15:10 backfill of the 37 affected pairs.

Root cause. The map was module-level:

Python
_seen = {}                       # hoisted for "reuse"

def find_pair(entries, target):
    for i, v in enumerate(entries):
        if target - v in _seen:
            return _seen[target - v], i
        _seen[v] = i
    return None

First call find_pair([3, 2, 4], 6) returns (1, 2) and leaves _seen = {3: 0, 2: 1, 4: 2}. Second call find_pair([2, 4], 6): at i=0, v=2, target - v = 4 is already in _seen from the previous call, so it returns (2, 0). Index 2 does not exist in the current batch: it names a row from the previous request.

Why it survived review. The happy path is a single batch, where the stale map is empty and the answer is correct. The bug needs a second call whose complement happens to sit in the first call's data.

Resolution. Scope the map to the call:

Python
def find_pair(entries, target):
    seen = {}
    for i, v in enumerate(entries):
        if target - v in seen:
            return seen[target - v], i
        seen[v] = i
    return None

Action items. Assert every returned index is within the current batch; add a canary batch with a known answer to the smoke test; cap any cache that outlives a request.

Trade-off worth recording. Prebuilding the map is not wrong: it is the right shape when you need all pairs, or when the batch is self-contained and you exclude self-pairing with an index check (seen[target - v] != i). Interleaving query and insert makes "the map holds only earlier elements" structural instead of a guard you have to remember. Cost is the same O(n) time and O(n) space per batch; the hoisted version traded that for O(total entries) memory that never shrank: 2.1M entries and ~180 MB RSS over the run.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

Given an unsorted array of integers, find the length of the longest run of consecutive values in O(n). Why do we only expand from elements whose predecessor is absent, and what does sorting cost instead?

Answer

Read "consecutive" as consecutive values, not adjacent positions: [1, 9, 3, 10, 4] holds the runs 3-4 and 9-10, so the answer is 2. Duplicates don't extend a run ([1, 1, 2] is 2) empty input is 0, and I'll assume O(n) extra memory is allowed.

The O(n) answer hashes the values, then expands only from run starts:

Python
def longest_run(nums):
    s = set(nums)              # O(n) build
    best = 0
    for x in s:                # iterate the set, not the list
        if x - 1 in s:
            continue           # x is not the start of a run
        y = x
        while y + 1 in s:
            y += 1
        best = max(best, y - x + 1)
    return best

The gate is what makes it linear. In a run s, s+1, ..., e exactly one element has its predecessor absent: the first. So each run is expanded once, and every extension step lands on a value not yet visited and never revisited: each of the n elements is touched at most once by an extension plus once by the outer scan, about 2n membership tests. Drop the gate and a run of length k costs 1+2+...+k = k(k+1)/2 steps. Over [1..1000] that's 500,500 lookups instead of roughly 2,000: quadratic, and it sails through every ten-element test you'd write first.

Two details bite in review. Iterate the set, not the list: with [1]*1000 + [2], the gate passes for every copy of 1, so the run is re-expanded a thousand times and the linearity quietly goes. And x + 1 overflows at INT_MAX in C++, Java and any fixed-width int: it wraps to INT_MIN and can weld two unrelated runs together; Python's arbitrary-precision ints make the snippet above safe, but a port is not. The complexity claim is also average-case: per Python's TimeComplexity page set membership is O(1) average and O(n) worst, so a hostile hash distribution degrades the whole thing to O(n^2). Say that rather than claiming unconditional linear.

Sorting instead: sort, then one scan counting positions where a[i] == a[i-1] + 1 and resetting otherwise. Timsort via sorted() and comparison sorting generally land at O(n log n), and Ω(n log n) is a lower bound for comparison sorting, so that path can never be linear.

hash setsort + scan
timeO(n) averageO(n log n)
extra spaceO(n)O(1) in place, O(n) if the input must survive
input orderpreserveddestroyed
worst caseO(n^2) on hash collisionsO(n log n) regardless of input

Choose sorting when you need the array ordered anyway, when memory is binding (a set of n integers typically costs several times the raw array in pointer-and-bucket overhead), or when you cannot accept the hashing worst case. Choose the set when the run length is the only thing you need and the data fits. Both are wrong on data that doesn't fit in memory: there you sort externally or walk a bitmap over the value range. If the range is small and dense, a bitmap or counting array is linear without hashing at all, which is the same technique with the hash function removed.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

How would you explain hash keys built from sequences without using the usual slogan?

Answer

Whether you can use a list or a joined string as a dict key comes down to one contract, and the joined-string case is the one that fails quietly.

A list can't be a dict key. A tuple can. A joined string can too, but only if no element can contain the separator, and that assumption is the part people forget to write down.

The mechanism is the __hash__/__eq__ contract: a dict hashes a key to a bucket, then compares candidates with ==. A type is usable as a key only if equal objects have equal hashes and the hash doesn't change while the object sits in the dict. Lists fail both: they're mutable, so CPython sets list.__hash__ = None and hash() raises. Tuples hash by content, recursing into their elements, so a tuple is hashable only if every element is.

Python
d = {}
d[(1, 2, 3)] = "tuple key"          # ok
d[[1, 2, 3]] = "list key"           # TypeError: unhashable type: 'list'

hash((1, 2, 3)) == hash((1, 2, 3))  # True
hash((1, [2]))                      # TypeError: unhashable type: 'list'

Trace: the first assignment calls hash((1, 2, 3)), gets an int, and stores. The second calls hash([1, 2, 3]) and raises before anything is inserted, so d still holds only the tuple key. hash((1, [2])) recurses into the element, calls hash([2]), and raises the same way.

The joined-string version is the one that bites in production, because it doesn't raise: it silently merges keys:

Python
"-".join(["a", "b-c"])   # 'a-b-c'
"-".join(["a-b", "c"])   # 'a-b-c'

Both sequences produce the string 'a-b-c', so the two lookups hit the same entry. This is not a hash collision: the two keys are equal strings, so the dict is behaving correctly and no bucket tuning or load-factor change helps. The fix is a serialisation that can't be ambiguous: a tuple, a frozenset if order shouldn't matter, or an explicit escaping or length-prefix scheme.

Two more things worth saying out loud. Order is part of the key: (1, 2) != (2, 1), so if the sequence is really a set of items, use frozenset. And in CPython a tuple's hash is recomputed on every call, there's no cached hash field, so a long tuple key pays O(n) per lookup; if that shows up in a profile, build the key once and reuse it.

When not to: don't reach for a sequence key if the natural key is a single scalar (an id, a UUID). And don't persist hash() output: string hashing is randomised per process (PYTHONHASHSEED), so the same string hashes differently across runs.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

Given a list of strings, encode it into a single string and decode it back exactly. Why does joining with a delimiter fail, when is length-prefixing sufficient, and what do empty strings and embedded delimiters do to each scheme?

Answer

Assume both ends run my code, the transport preserves every byte, and the strings are arbitrary: empty strings included, and containing anything. The contract is a lossless round trip, decode(encode(xs)) == xs for every list of strings. That property is the whole design constraint: the encoding has to be injective, or some list of strings is not recoverable.

Delimiter joining is not injective. Two different lists collide:

Python
",".join(["a,b", "c"])   # "a,b,c"
",".join(["a", "b,c"])   # "a,b,c"  -- same encoded string, different input

Empty strings break it a second way: ",".join(["", "a"]) is ",a", which is also what ",".join([",a"]) produces. And splitting is not the inverse of joining even when nothing contains the delimiter: checked against Java 21, "a,".split(",") returns ["a"] because trailing empty strings are dropped unless you pass a negative limit; Python 3.14's "a,".split(",") returns ['a', '']. Same input, two runtimes, two answers.

Escaping restores injectivity if the escape rule is one-to-one, CSV's quote-and-double (" becomes "") is the standard example, but decode turns into a character-by-character state machine and the bug surface moves into the escaping.

Length-prefixing removes the problem rather than patching it, because the decoder reads by count and nothing inside the payload is special.

Python
# Python 3.14
def encode(xs):
    parts = []
    for s in xs:
        b = s.encode("utf-8")                 # count bytes, not characters
        parts.append(str(len(b)).encode("ascii") + b"#" + b)
    return b"".join(parts)

def decode(data):
    xs, i = [], 0
    while i < len(data):
        j = data.index(b"#", i)               # ValueError on a truncated header
        n = int(data[i:j])
        i = j + 1
        if i + n > len(data):
            raise ValueError("truncated payload")
        xs.append(data[i:i+n].decode("utf-8"))
        i += n
    return xs

An empty string is 0#. A # sitting inside a string is just a byte. The prefix costs 2 bytes on payloads under 10 bytes (3#abc is 5 bytes for 3 bytes of data, 67% more) and 3 bytes on 10–99 (15% more on a 20-byte payload). Netstrings (5:hello,) and protobuf's length-delimited fields (varint length) are the same scheme with different header encodings.

Length prefixing is sufficient exactly when three things hold: the length field is self-delimiting. Fixed width, or decimal digits followed by a terminator that cannot be a digit; the length is measured in the units the decoder counts, i.e. bytes on the wire, which is why I encode to UTF-8 before measuring; and the transport is byte-preserving. When one of those fails (a text-only channel that mangles bytes, or a format I don't own) I end up base64-ing or escaping anyway, and at that point I use an existing framing instead of inventing one.

Failure modes I would guard: a header declaring 4 GB (cap it before allocating), a truncated tail (the bounds check above. Bare slicing silently returns fewer bytes), and a length counted in code points while the wire carries UTF-8. len("café") == 4 but len("café".encode("utf-8")) == 5, so the decoder desynchronises at the second string and the symptom shows up far from the bug. Build the payload with append and one join (append is amortised O(1), join is O(total bytes)); repeated s += piece is quadratic in general, and CPython's in-place optimisation is an implementation detail, not a contract. Encode and decode are both O(total bytes) time and space.

The CI check is a property test: random lists mixing empty strings, embedded separators and non-ASCII, assert decode(encode(xs)) == xs, plus truncated and over-long inputs must raise.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

When would you refuse a design because of grouping by a canonical key?

Answer

Refuse when the relation isn't an equivalence relation, or when the key you'd compute isn't injective on it. Those are the two hard stops. Cost, storage and migration are trade-offs you can argue; they aren't grounds for refusal.

Three conditions, in the order I'd check them.

1. The relation isn't transitive. Key grouping computes connected components: it assumes ab and bc implies a~c. "Within one edit" doesn't have that property.

Python
pairs = [("cat", "bat"), ("bat", "bad"), ("bad", "cad")]
# cat~bat, bat~bad, bad~cad  (one substitution each)
# cat vs cad: two substitutions -> not related

Union-find over those pairs yields one component {cat, bat, bad, cad}, putting cat and cad in the same group though they're two edits apart. If the product means "every member within one edit of every other", that's a clique, not a component, and no canonical key produces it. Refuse the key and ask which of the two the product actually wants.

2. The key is lossy. A key must satisfy key(a) == key(b) exactly when relation(a, b) holds. Sum-of-codepoints fails it:

Python
sum(map(ord, "ad")) == sum(map(ord, "bc"))  # 197 == 197, but they are not anagrams

The check that catches this is a property test, not an example: sample random pairs from the real corpus and assert key(a) == key(b) implies relation(a, b). ["eat", "tea", "tan"] will never expose it.

3. The key is unstable, or as expensive as the comparison it replaces. If the key is materialized and the normalization rule changes (Unicode NFC vs NFD, case folding, locale collation) every stored key is stale and groups split silently on deploy. And for long items, tuple(sorted(word)) is O(L log L) per item, the same order as the comparison the key was meant to avoid.

The distinction that decides most real designs: a key used for grouping must be injective; a key used for blocking only needs to be a superset filter. It may over-merge candidates as long as it never separates two items that belong together. Blocking plus pairwise comparison inside each block is the right structure when the relation is fuzzy.

ApproachCostCorrect whenBreaks when
Canonical keyO(n·k)relation is an equivalence, key injectivelossy key, non-transitive relation
Pairwise + union-findO(n²·c)relation arbitrary, n in the thousandsn large
Blocking + pairwiseO(n·k + Σ bᵢ²·c)key is a superset filterblock skew: one block holds most rows

Failure modes and how you see them. A lossy key shows up as groups that are too large and never as an error: detect it with the property test above. Block skew shows up in p99 latency, not the mean, because one block degenerates to O(n²); detect it by logging the block-size distribution. Key drift after a normalization change shows up as a group count that jumps on deploy; detect it by comparing group counts before and after.

So: refuse when the relation isn't an equivalence relation or the key isn't injective on it. Accept, with the key documented as the definition of the relation, when both hold.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

When is a direct-indexed array strictly superior to a hash map for key-value lookups, and where does that choice collapse?

Answer

Core answer (first 90 seconds). A direct-indexed array wins outright when three things hold at once: keys are integers in a bounded range $[0, U-1]$, density $\rho = n/U$ is high enough that the empty padding costs less than per-entry metadata, and $U \times \text{sizeof}(V)$ fits in L2. Then lookup is one load, base + k*stride, with no hash, no probe, no key comparison, no per-entry header. It loses on all three the moment keys go sparse, $U$ goes large, or values go big.

Why it wins. The array's cost is $U \times \text{sizeof}(V)$ and its lookup is a single address computation. A chained hash map pays per entry: libstdc++'s std::unordered_map allocates one node per entry holding a next pointer (8 B), a cached hash (8 B), the key, the value, plus allocator overhead. Call it 32 B of overhead on top of sizeof(K)+sizeof(V). It also keeps a bucket array sized to the next prime above $n$ at load factor 1.0.

Worked example. 100,000 live sessions, IDs drawn from $[0, 131072)$, value is an 8-byte pointer.

  • Array: $131072 \times 8 = 1{,}048{,}576$ B = 1 MiB. $\rho = 100000/131072 = 0.76$. Fits in a 1–2 MB L2.
  • Hash map: $100000 \times (8+8+32) = 4.8$ MB of nodes, plus 196,613 buckets × 8 B = 1.5 MB. Total ≈ 6.3 MB: L2-resident it is not; it lives in L3.

On recent x86 that is roughly 12–14 cycles for the array load versus 40–50 cycles for the L3 hit, before the hash function and the key comparison. The array also prefetches cleanly because consecutive keys are consecutive addresses; the hash map's nodes are scattered by the allocator.

The crossover, as arithmetic. Array memory is $U \cdot s_V$; hash map memory is $n(s_V + s_K + 32)$. The array wins when

$$\rho = \frac{n}{U} > \frac{s_V}{s_V + s_K + 32}.$$

For 8-byte keys and 8-byte values that is $\rho > 8/48 \approx 17%$. Two consequences worth saying out loud: with 1-byte values the threshold drops to $\rho > 1/41 \approx 2.4%$, so a byte-per-key table is worth it even when mostly empty; with 1 KiB values it rises to $\rho > 1024/1064 \approx 96%$, so a fat value type makes the array a loser unless it is almost perfectly dense.

Where it collapses.

  1. Sparse keys. $U = 2^{32}$, $n = 100{,}000$: the array wants $2^{32} \times 8 = 32$ GiB. mmap may hand back the virtual range, but the first touch of each page faults; RSS climbs until the OOM killer arrives. Detect with VmSize vs VmRSS in /proc/<pid>/status.
  2. TLB pressure. 32 GiB at 4 KiB pages is 8.4M pages against a ~1,500-entry L2 TLB, so every lookup pays a page walk. perf stat -e dTLB-load-misses shows it immediately.
  3. Clustered high keys. IDs in $[10{,}000{,}000, 10{,}100{,}000]$: unshifted, the array is $10{,}100{,}001 \times 8 \approx 81$ MB; normalized by $k - k_{\min}$ it is $100{,}001 \times 8 \approx 800$ KB. Normalization works for one contiguous cluster; two disjoint clusters and you are back to a hash map or a two-level index.
  4. Non-integer keys. Strings, UUIDs, tuples: there is no direct index, full stop.
  5. Absent vs. zero. If zero is a legal value you need a parallel validity bitmap, $U/8$ bytes, which shifts the crossover above.

Hash map failure modes, for symmetry. Adversarial keys that collide into one bucket degrade lookup to $O(n)$; watch max chain length (Java treeifies at 8). Rehashing at the load-factor threshold causes a latency spike: check the p99.9 bucket, not the mean.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

How would you reason about amortised append and growth factors in a system you own?

Answer

Amortised O(1) append rests on geometric growth: when the buffer fills, allocate a larger block and copy the old contents in. Because the block size multiplies while the number of appends between copies also multiplies, the copy cost spread across those appends is constant. The guarantee is amortised, not per-operation: the single append that triggers a resize is O(n).

The growth factor g is the knob. Resizes land at sizes 1, g, g², …, up to n, so total copy work for n appends is 1 + g + g² + … + g^k ≈ g·n/(g−1). Doubling gives ~2n copies; 1.5x gives ~3n; CPython's ~1.125x gives ~9n. Larger g means fewer resizes but more slack memory held; smaller g means less waste but more copying and more allocator churn. That trade-off is why most implementations land between 1.5x and 2x.

CPython is the outlier worth knowing. Its list grows by newsize + (newsize >> 3), roughly 1.125x, favouring memory over copy count:

Python
import sys
a = []
print(sys.getsizeof(a))              # 56 - empty list
for n in range(1, 10):
    a.append(n)
    print(n, sys.getsizeof(a))
# 1 88
# 2 88
# 3 88
# 4 88
# 5 120
# 6 120
# 7 120
# 8 120
# 9 184

Capacity jumps at 1, 5 and 9 elements: those three appends copy, everything between them is a pointer store into existing slack. The sizes decode as 56 + slots×8: 4 slots at 88, 8 at 120, 16 at 184.

Failure modes worth naming:

  • Claiming O(1) worst case. The resize append is O(n) and lands in tail latency even when throughput looks fine. A p99 spike in an append-heavy loop is the resize, not noise.
  • Growth factor too small. More copies, more GC pressure, more allocator churn: CPython's 1.125x is a deliberate memory-for-copies trade, not a default to copy into a hot path.
  • Growth factor too large. Wasted capacity, and for large elements the copy itself dominates the resize.

In a system you own: pre-size when the final count is known (a list built from a known-length source, or an array preallocated to capacity), and treat tail-latency spikes in append-heavy hot loops as a resize signal rather than a mystery. If append latency matters more than memory, raise the factor; if memory matters more, lower it, but measure, because the constant g·n/(g−1) is what you are actually trading.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

How does in-place array rearrangement change if the workload grows by two orders of magnitude?

Answer

The algorithm doesn't change. Two pointers, one pass, O(n) time and O(1) extra space at any n. What changes at 100x is the cost per element: the array leaves cache, so you pay DRAM bandwidth instead of L3 bandwidth, and the copy-to-a-new-array alternative stops being free.

Assumptions: int32 elements, single thread, x86-64 server at ~3 GHz, ~150 GB/s L3, ~12 GB/s single-core DRAM stream, 50% of elements survive.

C
// int32_t a[n]; drop every element equal to target, in place.
size_t compact(int32_t *a, size_t n, int32_t target) {
    size_t write = 0;
    for (size_t read = 0; read < n; read++) {
        if (a[read] != target)      // data-dependent branch
            a[write++] = a[read];   // write stream trails read stream
    }
    return write;                   // a[0..write) is the result
}
n = 1e6 (4 MB)n = 1e8 (400 MB)
ResidencyL3DRAM
Traffic (50% survive)6 MB600 MB
Memory floor~40 µs~50 ms
Branchy loop~2–3 ms~250 ms
4 KB pages touched1,024102,400
Copy alternative4 MB alloc, ~1k faults400 MB alloc, ~100k faults

Arithmetic: 1e6 elements read 4 MB and write 2 MB = 6 MB; at 150 GB/s that's 40 µs. 1e8 elements move 600 MB; at 12 GB/s that's 50 ms. 100x the data costs ~1250x the memory time, because bandwidth per byte drops ~12x when you leave cache. That is the change.

Three things that only bite at 100x:

TLB. 400 MB at 4 KB pages is 102,400 pages; the L2 TLB holds ~1,500–2,000 entries, so nearly every access misses. 2 MB huge pages cut it to 200 entries and remove the misses. At 4 MB the array is 1,024 pages and mostly stays resident.

The two streams separate. The write pointer trails by the number of removed elements, which grows with n. At 50% removal over 1e8 elements the average lag is 5e7 elements = 200 MB, so read and write touch different pages and double TLB pressure. At 1e6 the lag is 2 MB: same cache lines, effectively one stream.

Branch mispredicts don't amortize. The if is data-dependent; on random data the predictor is right ~50% of the time at ~15 cycles a miss, so ~7 cycles per element. That is a fixed per-element cost, so it scales linearly: ~2–3 ms at 1e6, ~250 ms at 1e8. It was invisible at 1e6 and is the wall-clock cost at 1e8. Branchless compaction (build a mask and compress (AVX-512 VPCOMPRESSD, or a scalar branchless store)) removes it and drops you to the memory floor. If the data is sorted or clustered the predictor does far better and the branch is nearly free.

When to copy instead: in-place wins at 100x when the array is a large share of the memory budget. The copy needs 2x the footprint, and first-touching 400 MB of cold pages costs ~50–100 ms in minor faults (100k pages at ~0.5–1 µs each) plus GC pressure in a managed runtime; in-place writes into pages already resident. Copy wins when you must keep the original, when the predicate is expensive enough that re-reading beats recomputing, or when the array is small enough that the allocation is noise.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

How would you test a claim that the system depends on prefix sums?

Answer

First, make the claim falsifiable. "The system depends on prefix sums" is two assertions wearing one sentence: a correctness claim (range answers are only right because the prefix array is there) and a latency claim (delete it and the endpoint misses SLO). I'd ask the claimant which one they mean and what number backs it: a design doc asserting constant-time lookups, or a profile showing the prefix array hot in the request path. Then I'd fix the assumptions I'm holding: same instance type, same production query distribution, same function signature on both paths.

Correctness first, because a latency test on a wrong path proves nothing. Ablate the prefix array behind the same interface and run real inputs through both:

Python
from itertools import accumulate
a = [3, 1, 4, 1, 5]
p = [0, *accumulate(a)]        # [0, 3, 4, 8, 9, 14]

def naive(i, j):               # the path if the prefix array is deleted
    return sum(a[i:j])

def pref(i, j):
    return p[j] - p[i]

naive(1, 4), pref(1, 4)        # (6, 6)

naive sums a[1:4] = [1, 4, 1] to 6; pref does p[4] - p[1] = 9 - 3 = 6. The differential harness is what runs millions of ranges. Do it on integers or with a tolerance: on float64 the two paths legitimately disagree by accumulated rounding, which is a different finding from "the claim is false," and conflating them wastes the experiment.

The latency claim has a sharp prediction: prefix-sum query cost is flat in range width k, a scan is linear in k. So the test is a sweep, not a single point. Replay sampled production queries, bucket them by k, and time both paths on identical inputs:

ClaimPrediction that would falsify itTest
Correctness depends on itSome input returns a different sum without the prefix arrayDifferential over sampled production ranges
Latency depends on itEndpoint p99 stays inside run-to-run noise after ablationA/B behind the same interface, both orders, repeated
It is hot at allThe prefix array is read roughly 0-1 times per requestCount reads per request in production

If endpoint p99 sits at 180 ms dominated by network and a database round trip (hypothetical), a query that saves a few hundred nanoseconds is invisible and the claim is decoration. The prefix array earns its place only when ranges are wide and frequent. Back-of-envelope for the write side, assuming each element read or written costs about the same and the working set is cached: naive costs about Q * k over Q queries, the prefix path costs about U * n to rebuild over U updates plus 2 * Q for the lookups, so prefix sums win only while Q / U > n / (k - 2). At n = 1e6 and k = 200 you need thousands of queries between every update; a high update rate inverts the claim and the array becomes pure overhead.

Watch the ways the test itself lies. Uniform-random ranges are the wrong workload (production ranges cluster short, shrinking the win) so replay a histogram of real k. Cache and JIT warmup flatter whichever path runs second, so run both orders and drop the first iterations. And a prefix array is usually a shadow copy of the data, so ablation also shifts memory bandwidth and cache pressure; measure on the real sized array, not a toy one.

What decides it is a number, not a narrative: if correctness is identical and ablation moves endpoint p99 by less than the noise floor, the system does not depend on prefix sums, whatever the doc says.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

What would you measure before treating prefix sums with a hash map as settled?

Answer

What to measure

Four numbers decide whether the hash-map version is settled, and none of them is the asymptotic complexity.

  1. Distinct prefixes vs n. The map holds one entry per distinct prefix sum, not one per element. On a 0/1 array of length 10^7 the distinct count can be a few thousand; on random 64-bit values it is ~n. Measure it with a one-pass set before committing to the approach: it is the single number that predicts memory.

  2. Peak RSS during the scan. On CPython 3.11 a dict holding 10^6 int→int entries is about 42 MB (40 MiB) for the table alone (sys.getsizeof), plus 28 bytes per distinct key int, so ~70 MB per 10^6 distinct prefixes. At 10^7 distinct prefixes that is ~700 MB, before the input list itself (a 10^7-element list of Python ints is ~360 MB: 8 bytes of pointer plus 28 bytes of int per element). That is the number that decides one-pass-in-RAM versus a sorted-prefix approach.

  3. Worst-case time on adversarial input. CPython's dict has no treeification: an adversary who controls the array can pick values so every prefix hashes to the same bucket, and the scan degrades to O(n²). Java's HashMap treeifies a bin at 8 entries once the table is at least 64, so it degrades to O(log n) per lookup instead. Measure random and crafted input; the ratio is the risk.

  4. max |prefix| against the integer width. Python ints do not overflow; Java and C++ running sums do. n values of magnitude M overflow int64 once n·M > 2^63−1: with M = 10^18 that is n = 10. Measure the max absolute prefix on real data, not the theoretical bound.

The check that can remove the map entirely

If every element is non-negative and k ≥ 0, a sliding window gives O(n) time and O(1) space. One pass to test the sign distribution is cheaper than any measurement above, and it runs first.

Alternatives and when each wins

ApproachTimeSpaceUse when
Sliding windowO(n)O(1)all values ≥ 0, k ≥ 0
Brute forceO(n²)O(1)n below a few hundred, or memory is the binding constraint
Hash map of prefixesO(n) avg, O(n²) worstO(distinct prefixes)mixed signs, n fits in RAM
Sorted prefixes + Fenwick treeO(n log n) worstO(n)attacker-controlled input, or you need a worst-case bound

The deciding criteria are the sign test, the memory budget against measurement 2, and whether the input is attacker-controlled.

Measuring it

Python
import tracemalloc, time, random

def count_subarrays(nums, k):
    counts = {0: 1}
    total = running = 0
    for v in nums:
        running += v
        total += counts.get(running - k, 0)
        counts[running] = counts.get(running, 0) + 1
    return total

nums = [random.randint(-10**6, 10**6) for _ in range(2_000_000)]
tracemalloc.start()
t0 = time.perf_counter()
count_subarrays(nums, 0)
dt = time.perf_counter() - t0
_, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
print(f"{dt:.2f}s  peak {peak / 2**20:.0f} MiB")

Read dt and peak off that, then rerun with nums replaced by an array whose prefixes are all congruent mod 2^61−1 (CPython's int hash) to get the collision worst case. tracemalloc sees Python allocations only; for the true figure use /usr/bin/time -v and read Maximum resident set size.

Correctness before cost

The seed counts = {0: 1} is what makes a subarray starting at index 0 count; drop it and [3], k=3 returns 0. That is a correctness bug, not a measurement, and a test should cover it before any of the numbers above matter.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

How does cache locality and the constant factor interact with rollback, and where do people ignore that?

Answer

I'll take rollback as aborting a write transaction: undoing work a transaction already did. If you meant rolling back a deploy, or a saga's compensating actions, the mechanism is the same: you pay to revisit state you already wrote, and the price is set by where that state lives.

The 90-second version

Rollback cost is (number of distinct pages you must visit again) times (cost per page visit). It is not the number of rows you changed. Locality sets both terms. A transaction that incremented one counter row 10,000 times touches one page and rolls back in microseconds. A transaction that updated 10,000 rows scattered one per page touches 10,000 pages and rolls back in whatever 10,000 random reads cost. Same row count, four orders of magnitude apart. Both are O(rows) asymptotically; the constant is the entire answer, and the constant is cache residency at the moment the abort runs.

Mechanism: two ways to undo, and where locality bites

Eager undo (InnoDB-style): each modification writes an undo record; rollback applies those records in reverse. Every record has to be applied to its original page, so if that page left the buffer pool, rollback pays a disk read. The reverse order helps: the last pages written are the most recently used, so they are the ones most likely still resident.

Lazy rollback (PostgreSQL-style): abort just marks the transaction aborted in the transaction status log (pg_xact). Every tuple version carrying that transaction's xmin becomes invisible to all readers, and the abort path returns after roughly one page write. Dead tuples are reclaimed later by VACUUM, which reads the table more or less sequentially.

The trade is a locality trade, not a correctness one. Eager undo runs while the touched pages are hot, so fewer misses, unless the transaction touched more distinct pages than the buffer pool holds, in which case it evicted its own earliest undo targets and the tail of the transaction is where the misses land. Lazy rollback makes the terminating transaction fast and pushes the cost to a background pass that pays full price unless it can scan sequentially. Either way the work exists; the design chooses who pays it and whether they pay with random reads or sequential ones.

Arithmetic

Buffer pool 8 GiB, 8 KiB pages, so about 1,000,000 pages resident. Table 100 GB, about 12,200,000 pages. Rows are 100 bytes, so roughly 80 rows per page. Two statements, each changing 1,000,000 rows:

statementrowsdistinct pages touchedrollback reads at 100 us/page
clustered: WHERE tenant_id = 421,000,000~12,500~1.3 s
scattered: WHERE id IN (1M ids)1,000,000~1,000,000~100 s

The clustered case touches 12,500 pages, which fit comfortably in the pool, so if they are still hot the IO is near zero and rollback is a memory walk. The scattered case touches about as many pages as the pool holds, so the first pages it wrote are gone by the time rollback reaches them. On local NVMe a random 8 KiB read is on the order of 100 us; on network-attached block storage it is closer to 1 ms, which turns the same rollback into roughly 1,000 s. Nothing in the row count tells you which of those you get.

Where people ignore this

A failed batch migration that ran for two hours before erroring holds its locks and its undo space for the whole rollback, because abort is not free. Measure abort separately from commit in your harness, and alert on transaction age, not on rows changed.

Migration windows get planned by row count. A 100,000,000-row single transaction has a table-sized rollback. Chunking to 10,000 rows per transaction bounds rollback to 10,000 rows and keeps each chunk's pages resident: that is a locality fix, not an asymptotic one.

Killing a query is expected to free resources immediately. Cancel and terminate start a rollback; locks and undo space stay held until it completes. Killing a large InnoDB transaction can sit in rollback for minutes.

The deferred form gets treated as free. PostgreSQL abort returns almost instantly, but the dead tuples bloat the table and the cost lands on VACUUM and on every later scan. The constant factor moved; it did not disappear.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

What is the smallest experiment that would change your mind about encoding state in the array itself?

Answer

The experiment is one input, not a benchmark.

Default position: encode marks in the array when the value domain is documented as 1..n and the caller does not need the array back. The smallest thing that would change my mind is a single adversarial input, an array containing 0 or a negative value, run against a set-based reference. If the two disagree, the in-place encoding is wrong, and no memory saving buys it back.

Python
# Python 3.12
def inplace(nums):                      # assumes values 1..n
    out = []
    for v in nums:
        i = abs(v) - 1
        if nums[i] < 0:
            out.append(abs(v))
        else:
            nums[i] = -nums[i]
    for i in range(len(nums)):
        nums[i] = abs(nums[i])
    return out

def reference(nums):
    seen, out = set(), []
    for v in nums:
        if v in seen: out.append(v)
        else: seen.add(v)
    return out

print(inplace([2, 0, 2]), reference([2, 0, 2]))

Trace of inplace([2, 0, 2]):

  • v=2 → i=1, nums[1]=0, not negative, so nums[1] = -0 = 0. The mark is a no-op.
  • v=0 → i=-1, nums[-1]=nums[2]=2, not negative, so nums[2] = -2.
  • v=2 → i=1, nums[1]=0, not negative, so nums[1] = 0 again.
  • restore → [2, 0, 2]; out = [].

Output: [] [2]. The in-place version silently misses the duplicate. That one disagreement is the mind-changer: the encoding is only correct when the domain excludes 0 and negatives, and the test costs one line.

Second experiment, only if the first passes. Now the question is whether the trick earns its fragility. Time both on n = 10^7 with values drawn from 1..n, on a machine with the array already resident:

  • in-place: two passes over the array, no allocation beyond the output list.
  • set-based: allocates a Python set holding up to 10^7 ints. Roughly 440 MB at ~44 bytes per entry (28-byte int object plus ~16 bytes of set table at a 2/3 load factor). That number is what decides it.

Labelled hypothetical: on a 16 GB box with 10^7 elements, the set version's peak RSS ran ~440 MB above the in-place version's, and the wall-clock difference was under 10%. So if the set fits comfortably, the extra memory is cheap insurance and I take it; if it pushes the process over its limit or shows up as a p99 pause, in-place wins.

Failure modes. The in-place trick fails silently, not loudly: it returns a wrong answer rather than raising. It also mutates the caller's array, if the caller holds a reference and reads it after the call, they see corrupted data unless you restore, and the restore pass is a second full traversal. Detection: a property test that generates inputs including 0, negatives, and duplicates, and asserts inplace(x) == reference(x). That catches it in CI before a caller does.

When not to use it. Any input contract that is not "distinct documented range, caller doesn't need the array": streaming input, values from an external system, arrays shared across threads. There, use a bitset (n bits = 125 KB for n=10^6) or a set and keep the array immutable.

Curated: · Written: · Reviewed:

Difficulty: Hard