Algorithmic Complexity & Code-Level Optimization Questions
Reasoning about the time and space complexity of code and applying local optimizations that materially change performance. Covers Big-O and amortized analysis, performance modeling, data-structure selection, hot-loop and allocation reduction, hardware-aware work such as cache locality, vectorization and false sharing, knowing when an algorithmic change beats micro-optimization, and the measurement practice that grounds those calls: flame graphs, hardware counters, and microbenchmarks that survive warmup, noise and statistical scrutiny. Emphasizes performance-aware coding grounded in complexity and measurement rather than premature tuning, scoped to code you can change rather than production incident response or capacity planning.
Explain why hash table lookup is said to be O(1) on average but O(n) in the worst case. Provide an amortized analysis of dynamic resizing when capacity doubles: derive the amortized cost per insert and show the steps of the argument. Finally, list production techniques to reduce worst-case lookup time (e.g., hash design, collision strategies, bounded worst-case guarantees).
Sample Answer
Direct answer
A hash table lookup is O(1) on average because a good hash function spreads keys roughly evenly across buckets, so each bucket holds close to a constant number of entries regardless of how many total entries exist. It degrades to O(n) in the worst case when many or all keys collide into the same bucket, turning that bucket into something you have to scan linearly, whether by bad luck, a poorly chosen hash function, or a deliberate attack.
Structured elaboration
Average-case argument: with n entries spread across m buckets using chaining, the average bucket holds n/m entries (the load factor). A well-designed hash table keeps the load factor bounded by a small constant (commonly resizing once it exceeds around 0.7-1.0), so the average chain length stays O(1), and a lookup does O(1) hashing plus O(1) expected chain traversal.
Worst case: if the hash function maps every key to the same bucket (either through bad luck with a weak hash, or through an attacker deliberately choosing keys that collide, a hash-flooding denial-of-service technique), that bucket's chain has length n, and looking something up in it costs O(n).
Amortized resizing derivation: when the table's load factor crosses its threshold, it allocates a new bucket array (typically double the size) and re-inserts every existing entry into it. This is structurally identical to the dynamic-array-doubling argument used for array appends: resizes happen when the table holds 1, 2, 4, 8, ... entries relative to its capacity, so the total re-insertion work across n inserts is bounded by the geometric series ∑2i<2n, plus the n individual insert costs, giving total work under 3n for n inserts, hence an amortized cost per insert of a small constant, O(1), by the exact same aggregate-method argument as array doubling.
Production techniques to reduce worst-case lookup time:
- Hash design: use a hash function with good avalanche properties and, for adversarial-input resistance, one that is keyed/seeded per process (so an attacker who knows the algorithm still can't predict collisions without knowing the runtime's random seed). Python randomizes string hashing by default (via
PYTHONHASHSEED) for exactly this reason. - Collision strategy: chaining (linked lists or small trees per bucket) versus open addressing (probing for the next free slot) trade off differently under high load factor and cache behavior; open addressing tends to be more cache-friendly at moderate load factors but degrades faster as the table fills.
- Bounded worst-case guarantees: some hash table implementations convert an over-long chain into a balanced structure once it passes a threshold. Java's
HashMap(Java 8+), for example, treeifies a bucket into a red-black tree once that bucket's chain length passes a threshold (with a further condition on overall table capacity), turning a pathological O(n) bucket into O(log n), a bounded-worst-case technique that doesn't require changing the hash function at all.
Worked example
Simulating the same doubling argument used for arrays, but for hash-table resizing: starting capacity 1, doubling at load factor 1.0, inserting 16 keys gives resize events at inserts 2, 3, 5, 9 (copying 1, 2, 4, 8 existing entries respectively), for total copy cost 1+2+4+8=15, plus 16 insert costs, for total work 31 across 16 inserts, an average of 31/16=1.9375 per insert, the identical arithmetic to doubling a dynamic array, because the underlying doubling argument is the same regardless of what's being resized.
Trade-offs and pitfalls
Treefying buckets (or any bounded-worst-case scheme) adds implementation complexity and a small constant-factor overhead to every operation in exchange for capping the damage from a bad key distribution; it's a mitigation for the worst case, not a way to make the average case faster. A common pitfall is assuming resizing alone protects against collision attacks: doubling the table helps when collisions are due to random bad luck (since a resize also re-hashes with the same hash function, so spreading only improves if the hash function itself is good), but it does nothing against an attacker who can predict the hash function's behavior and keeps choosing colliding keys regardless of table size, which is why seeding/randomizing the hash function is a separate and necessary defense from resizing.
Explain the differences between Big O, Big Theta (Θ), and Big Omega (Ω) notation. For each notation: provide a precise definition, one concrete algorithm example (e.g., insertion sort, binary search), and describe when an interviewer would expect each notation to be used. Discuss how constant factors and lower-order terms are treated.
Sample Answer
Direct answer
Big-O is an upper bound on growth rate ("grows no faster than"), Big Omega (Ω) is a lower bound ("grows no slower than"), and Big Theta (Θ) is a tight bound: both an upper and a lower bound at once, meaning the true growth rate is pinned down up to a constant factor. In everyday interview talk people say "O(n)" to mean "it's linear," but that loose usage blurs a real distinction the formal definitions make precise.
Structured elaboration
Formal definitions, each dropping constant factors and lower-order terms by design:
f(n)=O(g(n)) if there exist positive constants c,n0 such that f(n)≤c⋅g(n) for all n≥n0. (an upper bound: the true cost is at most this fast-growing)
f(n)=Ω(g(n)) if there exist positive constants c,n0 such that f(n)≥c⋅g(n) for all n≥n0. (a lower bound: the true cost is at least this fast-growing)
f(n)=Θ(g(n)) if f(n) is both O(g(n)) and Ω(g(n)): the true cost is sandwiched between c1⋅g(n) and c2⋅g(n) for large n.
Worked example 1, insertion sort: on a reverse-sorted array of length n, insertion sort does about 2n(n−1) comparisons and shifts (every new element has to walk past everything already placed), so its worst case is Θ(n2): it really is quadratic there, both bounded above and below by n^2. But on an already-sorted array, each element only needs one comparison against its neighbor before it's confirmed in place, so the best case is Θ(n). Because the best and worst cases belong to different growth classes, insertion sort AS A WHOLE ALGORITHM is correctly described only as O(n2) (an upper bound that holds for every input) and Ω(n) (a lower bound achieved by at least one input family). It is not Θ(n2) or Θ(n) overall, only within a specified case.
Worked example 2, binary search: on a sorted array of size n, each comparison halves the remaining search space, so the number of comparisons needed to narrow the window down to nothing is about log2n, and an UNSUCCESSFUL search always runs the halving all the way down, so unsuccessful search is Θ(logn) on every input. Successful search is the more interesting case, and the same rule used on insertion sort has to be applied honestly here: the input family where the target happens to sit at the very first probed midpoint returns after exactly ONE comparison, at any n (executed: for n=7 the first midpoint is index 3, for n=1023 it is index 511, for n=1,000,001 it is index 500,000, and each returns in 1 comparison). So binary search AS A WHOLE ALGORITHM is O(logn) and Ω(1), and it is Θ(logn) only within a specified case: the worst case, or unsuccessful search. The contrast with insertion sort is therefore NOT "binary search has no best-case family in a different class"; it is that binary search's best-case family is a vanishing fraction of inputs (one index out of n), whereas insertion sort's Θ(n) best case covers every already-sorted array, which is why quoting binary search as "Θ(logn)" without qualification is a common shorthand that a careful answer still has to label as the worst-case bound.
When an interviewer expects which notation: Big-O is the default ask ("what's the complexity of your solution?") because it's the guarantee you promise a caller: things will not get worse than this. Omega shows up when arguing a LOWER bound on a problem itself, not a specific algorithm: comparison-based sorting needs Ω(nlogn) comparisons in the worst case because there are n! possible orderings and each comparison can only rule out roughly half of the remaining possibilities, an information-theoretic argument, not a property of any one sorting algorithm. Theta is expected when a candidate is asked for a tight characterization of an algorithm whose best and worst case coincide (merge sort is Θ(nlogn) in every case), or when the interviewer wants to test whether the candidate understands that O alone never rules out an algorithm being faster than claimed.
Constant factors and lower-order terms: none of the three notations care about them. 3n2+50n+7 is Θ(n2), full stop, because as n grows the n2 term dominates the others. This is exactly why an asymptotically worse algorithm can still beat a better one for realistic input sizes (concretely: an algorithm costing 0.1⋅nlog2n actually runs faster than one costing 0.5n for every n below 32, and only loses once n passes that crossover, even though nlogn is the asymptotically worse growth rate): the notation answers "how does cost scale as n grows without bound," not "which one is faster for n=1,000."
Worked example
For n=5: insertion sort on [1,2,3,4,5] does 4 comparisons and 0 shifts (best case, linear); on [5,4,3,2,1] it does 1+2+3+4=10 comparisons and shifts, matching 25⋅4=10 (worst case, quadratic). For n=1,000,000: binary search needs ⌈log21,000,000⌉=20 comparisons in the worst case, and never more, which is the concrete sense in which the WORST case is tightly Θ(logn). It can need far fewer: a target sitting at index 500,000 (the first midpoint probed) is found in 1 comparison, so 20 is a tight upper bound and 1 is the lower bound, exactly the O-and-Omega-but-not-Theta situation insertion sort is in, just with a much thinner best-case family.
Trade-offs and pitfalls
A common mistake is announcing "Theta" for an algorithm when only an upper bound (worst-case Big-O) has actually been shown, and note that this trap catches textbook examples too: "binary search is Θ(logn)" is true of its worst case and of unsuccessful search, but false of the algorithm over all inputs, because a target at the first probed midpoint costs 1 comparison at any n; another is treating Big-O as a complete performance description when it says nothing about the lower bound, so an algorithm claimed O(n) could secretly always run much faster. Omega is most often about the PROBLEM's inherent difficulty (like the n log n sorting lower bound), and conflating that with "my particular algorithm's best case" is a frequent interview slip. Finally, remember that these classifications say nothing about constants: comparing a 0.5n algorithm against a 0.1⋅nlogn algorithm directly shows how a small constant can still lose once n passes a modest threshold (here, n=32), which asymptotic notation by design does not tell you.
A PyTorch model's activations dominate GPU memory usage during training. Propose practical strategies to reduce peak memory usage, and for each explain the likely effect on throughput and any numerical or implementation trade-offs.
Sample Answer
Direct answer
Attack peak activation memory with three levers that each trade something else for it: precision (store activations in fewer bits), compute (recompute activations instead of storing them), or batch composition (simulate one large batch out of several small ones). All three apply on a single GPU, which is why they come first. Multi-GPU sharding is a real fourth lever and it is scoped out below for a reason worth stating accurately rather than waved away.
1. Mixed precision
Storing activations and gradients in 16-bit floating point (fp16 or bf16) instead of 32-bit (fp32) roughly halves the memory footprint of every stored activation, and is usually a THROUGHPUT WIN, not a cost, on GPUs with hardware support for reduced-precision math.
Concrete worked example: an activation tensor shaped (batch=32, channels=256, height=56, width=56) has 32 x 256 x 56 x 56 = 25,690,112 elements. At 4 bytes per element (fp32) that is about 102.76MB; at 2 bytes (fp16) it is about 51.38MB, a saving of about 51.38MB for that ONE tensor, which compounds linearly across every layer's activations kept for the backward pass.
Numerical trade-off: fp16 has a much narrower exponent range than fp32 and can silently underflow small gradients to zero, so it needs loss scaling (multiplying the loss before backpropagation, then unscaling the gradients afterward) to stay numerically stable. bf16 keeps fp32's exponent range and gives up mantissa bits instead, which is why it generally does not need loss scaling at all, at the cost of coarser precision per value. Some operations, like softmax and batch-norm reductions, are typically still computed in fp32 even inside an otherwise mixed-precision model, "mixed" is selective, not everything switches.
2. Activation (gradient) checkpointing
Instead of keeping every intermediate activation for the backward pass, store only a subset of checkpoint activations and RECOMPUTE the ones in between during backward. Memory drops roughly in proportion to how sparsely you checkpoint, checkpointing every sqrt(L)-th layer of an L-layer network is the textbook square-root memory for extra-compute trade, at the direct cost of redoing part of the forward pass during backward, which lowers throughput because real floating-point operations are repeated rather than saved. The usual accounting is roughly one extra forward pass, so about a third more compute for a forward-plus-backward step, in exchange for activation memory falling from order L to order sqrt(L).
3. Gradient accumulation (the same trade, applied to batch size)
Run several smaller micro-batches, summing their gradients WITHOUT stepping the optimizer, then step once after N micro-batches, simulating an effective batch size of N times the micro-batch size while only ever holding one micro-batch's activations in memory at a time. This does not reduce total compute (per-sample forward and backward cost is unchanged), but it does cost wall-clock throughput relative to one large batch, since small micro-batches usually underutilize a GPU's parallel compute units compared to a single large batch that saturates them better.
4. Why multi-GPU sharding is scoped out here, stated correctly
It would be wrong to say distributed training only moves compute around. Plain DATA parallelism does not shard a single rank's activations at all (each rank holds its own local batch's activations in full), and parameter-sharding schemes of the ZeRO or FSDP family shard weights, gradients and optimizer states rather than activations. But TENSOR and SEQUENCE parallelism do split the activation tensors themselves across ranks, so per-GPU activation memory genuinely falls with the degree of parallelism. The reason to reach for the three levers above first is not that sharding fails to help activations, it is that sharding requires more than one GPU, a change to the model's parallelism topology, and added collective-communication traffic on every layer, whereas precision, checkpointing and accumulation are all configuration-level changes on the hardware already in hand.
A rarer, more advanced option worth a brief, clearly-labeled mention: reversible layers (used for example in RevNets) let a layer's input be exactly reconstructed from its output during backward instead of being stored at all. This is a much less commonly asked interview topic than the three above, since it requires choosing a reversible architecture from the start rather than retrofitting it onto an existing model.
Trade-offs and pitfalls
Mixed precision is close to a free win and is usually the first lever worth trying. Checkpointing and gradient accumulation both explicitly buy memory by spending compute time, so applying all three at once can leave a model memory-safe but meaningfully slower per epoch than expected, worth quantifying which specific layers actually need checkpointing rather than checkpointing the entire network by default.
Explain function inlining and loop unrolling as compiler optimizations. Provide an example where manual loop unrolling in C/C++ might improve performance for a small fixed-size kernel in a deep learning library, and describe the trade-offs such as code size and instruction cache pressure.
Sample Answer
Direct answer. Inlining replaces a function call with the function's body directly at the call site, removing call/return overhead (pushing arguments, jumping, restoring the stack) and opening the door for further optimization across what used to be a call boundary. Loop unrolling replaces a loop with several copies of its body executed per iteration, reducing how often the loop's own bookkeeping (incrementing the counter, checking the exit condition, branching back) runs relative to the actual work done.
Structured elaboration.
- Inlining is most valuable for small, frequently-called functions (a getter, a small math helper) where the call overhead is a meaningful fraction of the function's own work; the compiler (or an explicit
inlinehint, which modern compilers treat as advisory, not a command) decides based on function size and call frequency. - Loop unrolling trades loop-control overhead for code size: instead of one comparison-and-branch per element, an unrolled-by-4 loop does one comparison-and-branch per 4 elements, and also gives the compiler more independent instructions per unrolled block to schedule across execution units, which can improve instruction-level parallelism (ILP, how many independent instructions a core can execute concurrently).
Worked example. A small fixed-size kernel common in deep learning libraries, e.g. a 4-tap FIR-style dot product used inside a larger operator, is the standard illustration, and it repays being precise about what the manual version actually buys, because a compile-time-known trip count of 4 is exactly the case an optimizing compiler already handles for you:
// Rolled: at -O1 and below, the loop's own bookkeeping (compare + branch)
// runs once per element. At -O2 the compiler already fully unrolls this,
// because the trip count of 4 is a compile-time constant.
float dot4(const float* a, const float* b) {
float sum = 0.0f;
for (int i = 0; i < 4; ++i) sum += a[i] * b[i];
return sum;
}
// Manually unrolled: no loop bookkeeping, and identical work to the version
// above once the compiler has unrolled that one. Note what it does NOT buy:
// the four multiplies are independent, but the four accumulating adds still
// form a single serial dependency chain, exactly as in the rolled version.
float dot4_unrolled(const float* a, const float* b) {
return a[0]*b[0] + a[1]*b[1] + a[2]*b[2] + a[3]*b[3];
}
// This is the rewrite that actually adds instruction-level parallelism:
// two independent accumulation chains joined by one final add, halving the
// dependency-chain length. The compiler is not allowed to do this for you,
// because reassociating floating-point addition changes the result.
float dot4_two_chains(const float* a, const float* b) {
return (a[0]*b[0] + a[1]*b[1]) + (a[2]*b[2] + a[3]*b[3]);
}
Reading the generated code rather than assuming is the habit worth having here. At -O2 the rolled and the manually unrolled versions come out the same shape: no loop, no compare, no branch, four load pairs and a chain of fused multiply-adds accumulating into one register. The manual unroll therefore wins only where the compiler has not unrolled for you, which for a constant trip count of 4 means only at lower optimization levels (at -O1 the loop does survive). What the manual rewrite genuinely can buy, and what the compiler is forbidden from doing on its own, is splitting the accumulation into independent chains: floating-point addition is not associative, so reassociating changes the result, and only the programmer can decide that is acceptable. That is what dot4_two_chains does, and it is why hand-written reduction kernels carry several partial accumulators. It also gives the generalization for the large-trip-count case: unrolling a reduction loop by 4 without also introducing 4 separate accumulators leaves the latency chain exactly as long as it was and gains close to nothing.
Trade-offs & pitfalls.
- Code size and instruction-cache pressure. Both inlining and unrolling grow the compiled code. A function inlined at every call site, or a loop unrolled by a large factor, can push the hot path outside the instruction cache (i-cache, the CPU's cache for fetched instructions rather than data), turning a compute win into a fetch-stall loss; this is why aggressive unrolling factors (16x, 32x) sometimes make code slower, not faster, once the working code no longer fits in i-cache.
- Diminishing and even negative returns once the trip count is small and fixed (like the 4-tap example): full unrolling is a clear win. For large or variable trip counts, unrolling by a small factor (2x-4x) to help ILP while leaving a remainder loop for the tail is the usual compromise.
- Beyond manual unrolling (a rarer, more advanced level of this same trade-off), ML compiler stacks automate exactly this decision at a much larger scale: operator fusion combines multiple kernel launches into one to remove call/launch overhead (the inlining idea applied to whole operators), and auto-tuning frameworks (e.g. XLA, TensorRT) search over unrolling factors, tile sizes, and fusion choices per target hardware rather than relying on a human-chosen unroll factor. This is good to be aware of but is not the first thing to reach for in a hand-written kernel; the fixed-size manual case above is the interview-relevant baseline.
You must choose a data structure to support: insert(user_id), exists(user_id), memory budget 512MB, dataset up to 100M unique user IDs, and occasional false positives are acceptable but false negatives are not. Compare Bloom filter, hash set, and bitset (sparse/roaring), estimate memory per structure, and justify your choice.
Sample Answer
Direct answer
A Bloom filter is the right structure here: its error profile (possible false positives, never false negatives) matches the requirement exactly, and at 100 million user IDs it fits comfortably within a 512 MB budget, roughly 115-180 MB depending on the false-positive rate chosen, versus a plain hash set or a dense bitset which either blow the budget or require an assumption about the ID space that the problem doesn't guarantee.
Structured elaboration
A Bloom filter is a bit array plus k independent hash functions: inserting a key sets k bits (one per hash function's output position); checking a key reads those same k positions and reports "possibly present" only if ALL of them are set, "definitely absent" otherwise. This is exactly why it can never produce a false negative (if a key was inserted, all k of its bits are guaranteed set), but it can produce a false positive (some other combination of inserted keys happened to set all k of a different key's bit positions by coincidence).
The optimal number of bits per element for a target false-positive rate p is:
nm=−(ln2)2lnp
and the optimal number of hash functions is:
k=nmln2
For n=100,000,000 users and a 1% target false-positive rate: m/n=−ln(0.01)/(ln2)2=4.605/0.4805≈9.585 bits per element, so m≈958,500,000 bits ≈114.3 MiB, using k≈9.585×0.693≈6.6→7 hash functions. Even tightening to a 0.1% false-positive rate only raises this to about 14.4 bits per element, roughly 171 MiB total with k≈10 hash functions, still well under the 512 MB budget, leaving substantial headroom for the actual bit array's memory-alignment overhead and any auxiliary bookkeeping.
A plain hash set storing the actual user IDs avoids false positives entirely but costs far more memory per element: a hash set of 8-byte integer IDs, accounting for typical per-entry overhead (a pointer/reference plus bucket-array slack at a sane load factor, and dramatically more if IDs are boxed objects rather than primitives, which is the default in many managed-language hash-set implementations), realistically lands somewhere between 16 and 48+ bytes per entry. At 100 million entries that is 1.6 GB to 4.8+ GB, several times the 512 MB budget even under the most favorable (primitive, unboxed) implementation assumption.
A bitset (plain or compressed/roaring) is extremely cheap IF the user IDs map onto a compact, mostly-dense integer range: a plain bitset over a domain of size D costs exactly D/8 bytes regardless of how many are actually set, so a dense range of 100 million sequential IDs costs about 12.5 MB, trivially within budget. But the problem states user_id in the abstract, not "a dense integer index," and real user identifiers are frequently sparse, non-sequential, or string-like (UUIDs, opaque tokens); over a large sparse ID space, a plain bitset is infeasible (you'd need one bit per possible ID value, not per actual user), and a compressed variant like a roaring bitmap only helps when the set IDs cluster, degrading toward hash-set-like memory use for a uniformly scattered 64-bit ID space, which is the worst case a general-purpose "exists" structure needs to tolerate.
Worked example
The 1% false-positive-rate Bloom filter sizing above IS the worked example: ~114.3 MiB total bit-array size for 100 million entries and 7 hash functions, comfortably inside 512 MB, versus a hash set's 1.6-4.8+ GB estimate for the same 100 million entries, a difference of well over an order of magnitude that makes the Bloom filter the only one of the three options that reliably fits the budget without relying on an unstated assumption about how the user IDs happen to be distributed.
Trade-offs and pitfalls
The Bloom filter's core limitation is that it cannot support deletion (in its basic form) without extra structure (a counting Bloom filter trades some memory efficiency for delete support), and it cannot enumerate its members, only answer membership queries, both fine for this problem's stated shape (insert and exists only) but worth flagging as constraints if the requirements later grow. The most common mistake in this exercise is reaching for a hash set by default because it's the familiar, exact structure, without first checking whether "exact" is actually needed: the problem explicitly says occasional false positives are ACCEPTABLE, which is the strongest possible hint that a Bloom filter's error profile is not just tolerable but a genuinely good fit, not a compromise.
Unlock Full Question Bank
Get access to all Algorithmic Complexity & Code-Level Optimization interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.