Time and Space Complexity Analysis Questions
Reasoning about algorithmic efficiency: Big-O/Theta/Omega notation, amortized analysis, recurrence solving, and the time-versus-space trade-off. Covers deriving bounds from code, comparing candidate approaches, and communicating complexity clearly under interview pressure. The analytical layer applied across every algorithm topic.
State the Master Theorem for recurrences of the form T(n) = a*T(n/b) + f(n), including all three cases and the regularity condition for case 3. Apply it to solve T(n) = 2T(n/2) + Theta(n), naming which case applies and why.
Sample Answer
Direct answer: For T(n)=a⋅T(n/b)+f(n), compare f(n) against nlogba: Case 1 (f grows slower) gives T(n)=Θ(nlogba); Case 2 (f grows at the same rate) gives T(n)=Θ(nlogbalogn); Case 3 (f grows faster, plus a regularity condition) gives T(n)=Θ(f(n)). For T(n)=2T(n/2)+Θ(n): here a=2,b=2, so nlogba=nlog22=n1=n, which matches f(n)=Θ(n) exactly - this is Case 2, giving T(n)=Θ(nlogn).
Structured elaboration
T(n)=aT(bn)+f(n),a≥1, b>1Let nc=nlogba be the "watershed" function.
- Case 1: f(n)=O(nc−ϵ) for some ϵ>0 (f is polynomially smaller). Then T(n)=Θ(nc) - the recursive subdivision dominates.
- Case 2: f(n)=Θ(nc) (f matches the watershed). Then T(n)=Θ(nclogn) - an extra log factor from the logbn levels of recursion each contributing equally.
- Case 3: f(n)=Ω(nc+ϵ) for some ϵ>0 (f is polynomially larger), AND the regularity condition af(n/b)≤kf(n) holds for some k<1 and large n. Then T(n)=Θ(f(n)) - the work done outside the recursive calls dominates.
Worked example
Applying to T(n)=2T(n/2)+Θ(n) (this is exactly mergesort's recurrence): a=2, b=2, f(n)=Θ(n).
nlogba=nlog22=n1Since f(n)=Θ(n)=Θ(n1), this is Case 2. So:
T(n)=Θ(nlog22logn)=Θ(nlogn)Verified by direct expansion of the recursion tree: at depth k, there are 2k subproblems each of size n/2k, each contributing Θ(n/2k) work at that level, so total work per level is 2k⋅Θ(n/2k)=Θ(n) - CONSTANT per level. There are log2n levels (until subproblems reach size 1), so total work is Θ(n)×log2n=Θ(nlogn), matching the Master Theorem result exactly - this is mergesort's well-known Θ(nlogn) bound.
Trade-offs & pitfalls
- The Master Theorem only applies to recurrences of EXACTLY this shape - a subproblems of EQUAL size n/b, plus f(n) extra work. Recurrences with unequal subproblem sizes (like T(n)=T(n/3)+T(2n/3)+n) need the recursion-tree or Akra-Bazzi method instead.
- Case 3 requires the regularity condition, which is easy to forget - most textbook f(n) (polynomials) satisfy it automatically, but it's worth naming explicitly when asked to "state all three cases."
- A common gap between cases (where f(n) is neither polynomially smaller, equal, nor polynomially larger than nc - e.g. f(n)=nc/logn or f(n)=ncloglogn) means the Master Theorem simply doesn't apply, and you need the recursion-tree method or a generalized (Akra-Bazzi-style) version instead.
Compare dynamic programming and greedy strategies using an example where greedy provably fails but DP succeeds (for example, coin change with a non-canonical coin system, or weighted interval scheduling versus a naive earliest-finish-time greedy). Explain, in general terms, what property a problem needs (optimal substructure without the greedy-choice property) for DP to be necessary rather than greedy sufficing.
Sample Answer
Direct answer: Greedy algorithms make the locally-best choice at each step and never reconsider it; they only produce a globally optimal result when the problem has the "greedy-choice property" (a locally optimal choice is always part of SOME globally optimal solution). Dynamic programming instead considers all relevant sub-solutions and combines them optimally, which is necessary whenever a problem has optimal substructure but LACKS the greedy-choice property - meaning an early locally-good choice can foreclose a better global outcome.
Structured elaboration
The classic contrast is coin change with a non-canonical coin system. With coins {1, 3, 4} and target 6: greedy (always take the largest coin that fits) picks 4, then 1, then 1 - three coins (4+1+1). The optimal answer is two coins: 3+3. Greedy fails here because taking the 4-coin first was locally attractive (it reduces the remaining amount fastest) but forecloses the better 3+3 solution - the greedy-choice property does not hold for this coin system. DP instead considers, for every amount from 0 up to the target, the best way to reach it using any allowed coin as the LAST coin used, guaranteeing the true optimum is found because every combination is implicitly considered via the subproblem recurrence, not just the first-glance-best one.
A cleaner illustration: weighted interval scheduling versus a naive earliest-finish-time greedy. Greedy-by-earliest-finish-time is actually PROVABLY OPTIMAL for the UNweighted version (maximizing the number of non-overlapping intervals selected) - the greedy-choice property genuinely holds there. But once intervals carry different WEIGHTS (values), earliest-finish-time greedy can pick a low-value interval that blocks a much higher-value overlapping one - here DP (considering, for each interval sorted by end time, the better of "skip it" versus "take it plus the best solution among intervals compatible with it") is required to guarantee optimality.
Worked example
Coin change with coins {1, 3, 4}, target 6, computed both ways:
def greedy_coin_change(coins, target):
coins = sorted(coins, reverse=True)
count = 0
used = []
remaining = target
for c in coins:
while remaining >= c:
remaining -= c
used.append(c)
count += 1
return count, used
def dp_coin_change(coins, target):
INF = float('inf')
best = [0] + [INF] * target
choice = [None] * (target + 1)
for amt in range(1, target + 1):
for c in coins:
if c <= amt and best[amt - c] + 1 < best[amt]:
best[amt] = best[amt - c] + 1
choice[amt] = c
return best[target]
print(greedy_coin_change([1, 3, 4], 6))
print(dp_coin_change([1, 3, 4], 6))
Executed: greedy returns (3, [4, 1, 1]) - 3 coins. DP returns 2 - matching the known optimal 3+3 solution, confirming greedy's suboptimality on this coin system directly, not just by assertion.
Trade-offs & pitfalls
- Greedy IS the right (and much cheaper - typically O(n log n) for a sort plus a linear pass, versus DP's often O(n^2) or worse) choice whenever the greedy-choice property provably holds for your specific problem - don't reach for DP out of caution when a proof of greedy correctness is available (e.g. the unweighted interval scheduling case, or canonical coin systems like standard currency denominations, where greedy IS provably optimal).
- Recognizing whether a coin system is "canonical" (greedy-safe) in general is itself a non-trivial problem - when in doubt about a NEW, unfamiliar constraint set, default to DP unless you can specifically prove the greedy-choice property holds.
- A wrong greedy solution often looks superficially reasonable (3 coins isn't obviously wrong without comparing to the true optimum) - this is exactly why validating against a DP or exhaustive reference on small test cases is worth doing before trusting a greedy approach in production.
Explain the general trade-off between trading memory for speed and vice versa: precomputing/caching a result versus computing it on demand. Give a concrete example (a lookup table, a materialized aggregate) and describe the decision criteria - update frequency, staleness tolerance, and available memory - that determine which way to lean.
Sample Answer
Direct answer: The core trade-off is: spend memory now (precompute, cache, or store a lookup table) to save time later, or spend time recomputing on demand to save memory. Which way to lean depends on three factors: how often the result is reused, how tolerant the system is of stale/out-of-date results, and how much memory is actually available.
Structured elaboration
Classic precompute-vs-on-demand examples:
- A lookup table of precomputed values (e.g. factorials up to 1000, or a static configuration derived from rarely-changing source data) trades O(table size) memory for O(1) lookup, versus recomputing each value in whatever time the computation naturally takes.
- A cache of expensive function results (e.g. a memoization cache, or an application-level cache in front of a slow downstream service) trades memory for avoiding repeated work, valuable when the SAME inputs recur.
The decision criteria:
- Reuse frequency: if a value is computed once and never needed again, caching it wastes memory for no benefit; if it's requested repeatedly, caching pays for itself quickly.
- Staleness tolerance: if the underlying data changes and the cached/precomputed value must reflect changes promptly, you need invalidation logic (itself a real engineering cost) or must accept some staleness window.
- Available memory: precomputing an entire table only works if it fits in your memory budget - for a combinatorially large input space, on-demand computation (possibly with a bounded LRU (least-recently-used) cache for the hot subset) is the only option.
Worked example
Consider a service computing an expensive per-user recommendation score, requested on average 5 times per user session. Precomputing (caching) the score after the first computation means requests 2-5 are O(1) lookups instead of paying the full computation cost again - a 5x reduction in total compute for that session, at the cost of holding the cached score in memory for the session's duration. If instead each user only ever requested the score ONCE, caching would add memory overhead (allocating and eventually evicting a cache entry) with zero reuse benefit - the "precompute and cache" decision is only a net win when the reuse count exceeds roughly the overhead ratio of caching versus recomputing, which for a cheap computation might mean caching isn't worth it at all.
Trade-offs & pitfalls
- Caching introduces a NEW correctness concern (staleness/invalidation) that a pure recompute-on-demand approach doesn't have - "correct but occasionally slow" is sometimes preferable to "fast but occasionally wrong," depending on the domain (financial data usually can't tolerate staleness; a recommendation score usually can).
- Precomputing a full table only makes sense when the input space is small/bounded enough to enumerate - for an unbounded or combinatorially large input space, you need either an on-demand approach or a BOUNDED cache (with an eviction policy) covering just the hot subset.
- The "free lunch" case is when precomputation happens once, amortized across many users/requests, and the underlying data changes rarely (e.g. compiling a regex once at startup rather than on every request) - here there's essentially no downside, which is why this specific pattern (compute-once-at-startup) is nearly always a correct default when applicable.
Explain the Quickselect algorithm for finding the k-th smallest (or largest) element in an unsorted array. State its average-case and worst-case time complexity, and explain how the median-of-medians pivot-selection strategy guarantees O(n) worst-case time at the cost of a larger constant factor.
Sample Answer
Direct answer: Quickselect finds the k-th smallest element in expected O(n) time by partitioning like quicksort but recursing into only the ONE side that contains the target rank (instead of both sides, as quicksort does) - its worst case is O(n^2) with a poor pivot choice, but the median-of-medians pivot-selection strategy guarantees O(n) worst-case at the cost of a larger constant factor.
Structured elaboration
- Like quicksort, pick a pivot and partition the array so elements less than the pivot come before it and elements greater come after.
- Unlike quicksort, once partitioned, you know which side contains the k-th smallest element (compare k against the pivot's final index) - recurse into ONLY that side, discarding the other entirely.
- Because each recursive call operates on roughly half the previous size (with a good pivot), the total work forms a geometric series (n+n/2+n/4+⋯) that sums to O(n), not O(n log n) - this is the key difference from quicksort, which must recurse into BOTH halves and thus sums to O(n log n).
- Worst case: an adversarial or unlucky pivot choice (always picking the smallest or largest remaining element) means each partition only shrinks the problem by one element, giving O(n) + O(n-1) + ... = O(n^2), identical in shape to quicksort's worst case.
- Median-of-medians: guarantees a pivot that is provably within the 30th-70th percentile of the current subarray (by recursively finding the median of medians of small groups), which bounds the worst case to O(n) - but the overhead of this more careful pivot selection makes its constant factor noticeably worse than simple random-pivot quickselect for typical inputs, so it's rarely used in practice outside of guaranteeing worst-case bounds for adversarial-input-resistant systems.
Worked example
Finding the median (n=1,000,001, k=500,000) with random-pivot quickselect: expected work is O(n) with a small constant (empirically close to 2n comparisons on average across many pivot choices), while the true worst case (vanishingly unlikely with a randomized pivot, but possible with a naive fixed-first-element pivot on adversarial/sorted input) would degrade to roughly (2n)≈5×1011 comparisons - the gap between expected and worst case is enormous, which is exactly why RANDOMIZED pivot selection (not median-of-medians) is the standard practical choice: it makes the O(n^2) worst case exponentially unlikely to occur by chance, without median-of-medians' extra constant-factor overhead.
Trade-offs & pitfalls
- Randomized-pivot quickselect is the default real-world choice: expected O(n), simple to implement, and the adversarial worst case requires the attacker to know your specific pivot-selection randomness, which is infeasible if properly seeded.
- Median-of-medians is the answer when you need a hard WORST-CASE guarantee regardless of adversarial input (e.g. exposed to untrusted, potentially crafted data) - know that it exists and why it works, even though it's rarely the practical default.
- Quickselect is NOT stable and mutates (partitions) the input array in place unless you copy first - both worth flagging as a caveat if the caller needs the original order/array preserved.
Explain how hash tables handle collisions via separate chaining versus open addressing, including the average-case and worst-case complexity of get/put/delete under each. Then explain how an attacker who can choose the keys can degrade every lookup to O(n) (a hash-flooding attack), and what mitigations (randomized hash seeding, safer hash functions) restore the average-case guarantee.
Sample Answer
Direct answer: Separate chaining stores colliding keys in a linked list (or small array/tree) per bucket; open addressing (linear/quadratic probing, double hashing) stores every key directly in the table itself, probing to the next slot on collision. Both give average-case O(1) get/put/delete under a good hash function and bounded load factor, but an attacker who can choose (or predict) keys that all hash to the same bucket can force every operation to O(n) - a real denial-of-service vector, not just a theoretical curiosity, mitigated by randomized hash seeding at process startup and hash functions resistant to seed-independent collision construction.
Structured elaboration
- Separate chaining: each bucket holds a small collection (commonly a linked list, or - in some modern implementations like Java 8+'s HashMap - a balanced tree once a bucket grows large) of all keys hashing there. Lookup cost is O(1 + chain length); with load factor kept bounded, expected chain length is O(1).
- Open addressing: on collision, probe subsequent slots (linear: next slot; quadratic: quadratically-increasing offsets; double hashing: a second hash function determines the probe sequence) until an empty slot is found. Avoids the pointer-chasing overhead of chaining (better cache locality, since probing stays within the contiguous backing array), but degrades faster as load factor approaches 1 (must keep load factor well below 1, commonly under 0.7, whereas chaining degrades more gracefully).
- The attack: if the hash function is known (or its output is predictable, e.g. a naive non-cryptographic hash with a fixed seed) and an attacker controls input keys (e.g. HTTP form-field names, JSON keys), they can construct a large set of keys that all collide into the same bucket(s), degrading every operation from O(1) to O(n) and creating an algorithmic denial-of-service - a single request with thousands of colliding keys can pin a server's CPU.
Worked example
This is not hypothetical: this exact vulnerability class ("hash flooding") was responsibly disclosed and patched across essentially every major web-application language runtime around 2011-2012, after researchers demonstrated that a small POST request with carefully-crafted colliding form-field names could consume many CPU-seconds parsing what should have been a millisecond-scale request. The fix adopted across languages was randomizing the hash seed per-process at startup (so the attacker can't predict the collision-inducing keys ahead of time without knowing the runtime's random seed) and, in some cases, switching to collision-resistant hash functions (like SipHash) specifically designed to make seed-independent collision construction computationally infeasible even if an attacker can observe hash outputs.
Trade-offs & pitfalls
- "Average-case O(1)" is a claim about TYPICAL inputs, not a security guarantee - any system that hashes attacker-controlled keys needs the worst-case-resistant mitigations (randomized seeding, or a cryptographically-motivated hash), not just a "good enough in practice" hash function.
- Randomized per-process seeding means hash order becomes non-deterministic across process restarts - code that accidentally depends on hash-iteration order (a common latent bug) will surface intermittently once seeding is randomized.
- Open addressing's degradation is sharper (clustering effects can compound near a full table) than chaining's, so open-addressing implementations typically resize more aggressively (lower load-factor threshold) to stay safely away from the cliff.
Unlock Full Question Bank
Get access to all 27 Time and Space Complexity Analysis interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.