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.
Explain the trade-offs of mixed-precision training (using float16 activations and weights with an float32 master-weight copy). What memory and compute speedups does it give, and what numerical failure mode (gradient underflow) does it introduce and how is it typically mitigated (loss scaling)?
Sample Answer
Direct answer: Mixed-precision training uses float16 (half precision) for the bulk of the forward/backward computation - roughly halving memory for activations and weights, and often giving a 2-3x compute speedup on hardware with dedicated float16 throughput (e.g. tensor cores) - while keeping a float32 "master copy" of the weights for the actual parameter updates, to avoid precision loss from accumulating many small float16 updates. The main numerical risk is gradient UNDERFLOW: many gradient values, especially early in training or for small-magnitude parameters, can be too small to represent in float16's limited range, silently becoming zero and stalling learning for those parameters.
Structured elaboration
- Memory savings: float16 uses half the bytes of float32, directly halving the memory footprint of activations (often the dominant memory consumer during training) and allowing correspondingly larger batch sizes or larger models within the same memory budget.
- Compute speedup: modern accelerators (GPUs with tensor cores, or equivalent) often have SPECIALIZED hardware for float16 (or bfloat16) matrix multiplication that achieves significantly higher FLOPs/second than the same operation in float32 - the speedup is a hardware property, not simply "half the bits, so half the time."
- Master weights: gradients and weight updates are typically small relative to the weight's current value, especially late in training with a small learning rate; accumulating these small updates directly into a float16 weight can lose precision entirely (the update rounds to zero due to float16's limited mantissa). Keeping a float32 master copy, updating THAT with full precision, and casting down to float16 for the next forward pass avoids this compounding precision loss.
- Gradient underflow and loss scaling: float16's exponent range is much narrower than float32's - gradient values that are legitimately small (common, especially with certain activation functions or deep networks) can underflow to exactly zero in float16, effectively stopping that gradient's contribution to learning. The standard mitigation is LOSS SCALING: multiply the loss by a large constant (say 1024 or higher) before backpropagation, which proportionally scales up all gradients into float16's representable range, then divide the resulting gradients back down before applying them to the (float32) master weights - a mathematically equivalent computation that sidesteps the underflow, as long as the scaling factor doesn't itself cause the opposite problem (overflow) for large gradients.
Trade-offs & pitfalls
- Loss scaling needs a properly chosen (or dynamically adjusted) scale factor - too small doesn't prevent underflow, too large risks overflow (gradients becoming
inforNaN); production frameworks typically implement DYNAMIC loss scaling, automatically adjusting the scale factor based on whether overflow is observed. - Not every operation is safe in reduced precision - some (e.g. certain normalization statistics, or loss computations sensitive to precision) are typically kept in float32 even within an otherwise mixed-precision training run, a deliberate selective-precision design rather than an all-or-nothing switch.
- bfloat16 (an alternative 16-bit format with float32's exponent range but fewer mantissa bits) sidesteps the underflow/overflow range problem entirely at the cost of somewhat coarser precision within the representable range - increasingly preferred over float16 specifically because it avoids needing loss scaling at all, a meaningful simplification.
Implement an LRU cache in Python with get(key) and put(key, value) both running in O(1) time and a fixed capacity that evicts the least-recently-used entry on overflow. State the time and space complexity of each operation, then discuss what changes if the cache must be safe under concurrent access from multiple threads.
Sample Answer
Approach: Use Python's built-in collections.OrderedDict, which is a hash map that also maintains insertion/access order internally (backed by a doubly linked list under the hood) - move_to_end and popitem(last=False) give the O(1) reordering and eviction primitives directly, without hand-rolling the linked-list pointer surgery.
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
if capacity <= 0:
raise ValueError("capacity must be positive")
self.capacity = capacity
self.data = OrderedDict()
def get(self, key):
if key not in self.data:
return -1
self.data.move_to_end(key) # mark as most-recently-used
return self.data[key]
def put(self, key, value):
if key in self.data:
self.data.move_to_end(key)
self.data[key] = value
if len(self.data) > self.capacity:
self.data.popitem(last=False) # evict least-recently-used
Key points: get and put are each O(1) amortized because OrderedDict maintains its internal doubly linked list alongside the hash table, so move_to_end and popitem(last=False) are O(1) list-splice operations, not O(n) scans. Capacity is enforced on every put by evicting the oldest entry once size exceeds capacity.
Complexity: Both get and put are O(1) time. Space is O(capacity), since the cache never holds more than capacity entries.
Edge cases: capacity 0 is rejected explicitly (a cache that can hold nothing is a degenerate case worth guarding); updating an existing key's value correctly refreshes its recency without growing the cache past capacity; requesting a missing key returns a sentinel (-1 here, following the common LeetCode convention) rather than raising, though a production cache would more idiomatically raise KeyError or return None.
Worked example / execution verification
cache = LRUCache(2)
cache.put(1, 'a')
cache.put(2, 'b')
print(cache.get(1)) # promotes 1 to most-recent -> 'a'
cache.put(3, 'c') # over capacity, evicts 2 (least-recently-used)
print(cache.get(2)) # -1, was evicted
print(cache.get(1)) # 'a', still present
print(cache.get(3)) # 'c', still present
Executed: output is a, -1, a, c - exactly matching the hand-traced sequence from the conceptual companion question (key 2 is correctly evicted because the get(1) call promoted 1 ahead of it, leaving 2 as the least-recently-used entry when 3 was inserted over capacity).
Trade-offs & pitfalls
OrderedDictis not thread-safe - concurrentget/putcalls from multiple threads need an external lock (or a striped-lock / lock-free design, at the cost of significant added complexity) if this cache backs a multi-threaded service.- Hand-rolling the hash-map-plus-doubly-linked-list structure explicitly (rather than relying on
OrderedDict) is worth being able to do too - some interviewers specifically want to see the pointer manipulation, sinceOrderedDictis "using a library that already solved it." - For very large caches, consider whether the per-entry overhead of a linked-list node plus hash-map entry (roughly 3-4x a raw value's memory footprint in CPython) is acceptable, or whether a more compact structure (e.g. a ring buffer indexed by insertion slot, at the cost of O(capacity) eviction scans) is a better fit for the memory budget.
Compare full-batch gradient descent, mini-batch SGD, and pure SGD (batch size 1) on computational cost per epoch, memory overhead, and how batch size affects gradient-estimate variance and hardware (GPU) throughput. Why does throughput typically plateau past a certain batch size even though the asymptotic per-step compute keeps scaling?
Sample Answer
Direct answer: Full-batch gradient descent computes the gradient over the ENTIRE dataset of size N before each update - O(N) work per step, but very few steps needed since each step's gradient is exact. Pure SGD (batch size 1) computes a gradient from a single example - O(1) work per step, but needs many more steps and each step's gradient is a noisy, high-variance estimate. Mini-batch SGD (batch size b) is the practical middle ground, O(b) work per step with gradient variance that decreases as 1/b, and - critically for modern hardware - the per-step work is highly PARALLELIZABLE across the batch dimension on a GPU, which is why throughput doesn't simply plateau immediately as batch size grows from 1.
Structured elaboration
- Per-step cost: proportional to batch size b (O(b) forward+backward work), true for all three variants (full-batch is simply b=N, pure SGD is b=1).
- Gradient variance: averaging over b independent samples reduces the VARIANCE of the gradient estimate by a factor of b (standard error shrinks as 1/b) relative to a single-sample gradient - this is why larger batches give a more accurate (lower-variance) estimate of the true full-dataset gradient direction, at the cost of more compute per step.
- GPU throughput and batch size: a GPU has a large but FIXED amount of parallel compute capacity; for small batch sizes, the GPU is under-utilized (idle compute units, since there isn't enough parallel work to fill them), so increasing batch size increases THROUGHPUT (examples processed per second) roughly linearly at first. Past some batch size, the GPU's compute units are fully saturated, and further batch-size increases no longer improve throughput per unit time (you're now compute-bound, not parallelism-starved) - this is why throughput plateaus, not because the underlying O(b) per-step cost changes, but because the WALL-CLOCK cost of processing b examples stops decreasing per-example once hardware parallelism is maxed out.
Worked example
Consider a GPU with enough parallel compute to fully utilize itself at batch size 256 for a given model. At batch size 32, the GPU processes each step in roughly the SAME wall-clock time it would take at batch size 256 (both are "cheap enough" to fit within one wave of parallel execution, dominated by fixed per-step overhead like kernel launch latency, not by the actual per-example compute) - so throughput (examples/second) at batch 32 is roughly 8x lower than at batch 256, purely from underutilizing available parallelism. Increasing batch size from 256 to 1024 (4x), once the GPU is already saturated at 256, roughly QUADRUPLES the wall-clock time per step (now truly compute-bound, scaling with actual work) while processing 4x the examples - so throughput stays roughly flat past this point, confirming the plateau.
Trade-offs & pitfalls
- Very large batch sizes, beyond the GPU-saturation throughput benefit, introduce their own OPTIMIZATION-QUALITY trade-off separate from the raw throughput question: overly large batches can generalize worse (a well-documented empirical phenomenon, sometimes called the "generalization gap"), requiring learning-rate scaling and other adjustments to compensate.
- Memory, not just compute, constrains batch size in practice - larger batches need proportionally more memory for activations (as discussed in the dense-layer-complexity survivor), and can hit a hard memory ceiling well before hitting a compute-bound throughput plateau.
- The variance-reduction benefit of larger batches has DIMINISHING returns (1/b, not 1/b) - doubling batch size from 1024 to 2048 reduces gradient noise by only about 29% (since 1/2≈0.71), a much smaller relative improvement than the first doubling from 1 to 2, which is part of why very large batch sizes give diminishing optimization benefit even before hitting hardware throughput limits.
Prove that any comparison-based sorting algorithm requires Omega(n log n) comparisons in the worst case, using the decision-tree model. Then explain the caveat: how do non-comparison sorts like counting sort or radix sort achieve O(n) time, and why doesn't that contradict the lower bound?
Sample Answer
Direct answer: Any comparison-based sorting algorithm requires Ω(nlogn) comparisons in the worst case. The proof models any comparison sort as a binary decision tree: since there are n! possible orderings of the input and each leaf of the tree corresponds to one output ordering, the tree needs at least n! leaves, and a binary tree with n! leaves must have depth at least log2(n!), which is Θ(nlogn) by Stirling's approximation.
Structured elaboration
- Model any comparison sort as a binary decision tree: each internal node is a single comparison ("is ai<aj?"), each leaf represents one final determined ordering (permutation) of the input.
- A correct sort must be able to produce every one of the n! possible orderings for some input, so the tree needs at least n! distinct leaves.
- A binary tree of depth d has at most 2d leaves, so we need 2d≥n!, i.e. d≥log2(n!).
- By Stirling's approximation, log2(n!)=Θ(nlogn).
- The worst-case number of comparisons for ANY comparison-based algorithm equals the depth of the deepest leaf reached, so the worst case is Ω(nlogn) comparisons - this is a lower bound on every possible comparison-based algorithm, not just a property of one specific sort.
Worked example
For n=4: 4!=24 possible orderings. log2(24)≈4.585, so at least 5 comparisons are needed in the worst case for any comparison sort of 4 elements (you can't do it in 4). Mergesort on 4 elements uses at most 5 comparisons in its worst case - matching the lower bound essentially exactly, which is why mergesort/heapsort are called "asymptotically optimal" comparison sorts.
Trade-offs & pitfalls
- The bound applies only to COMPARISON-based sorts - it says nothing about algorithms that use more information than pairwise comparisons.
- Counting sort (O(n+k) for keys in range [0,k)) and radix sort (O(d(n+k)) for d-digit keys) beat nlogn because they never compare two elements directly - they use the numeric VALUE of keys to bucket them, which is extra information a black-box comparison oracle doesn't have. This does not contradict the lower bound; it sidesteps its assumption entirely.
- Practical caveat: counting/radix sort's better asymptotic complexity assumes bounded/small key ranges or fixed-width keys; for arbitrary-precision or highly varied keys, the "k" or "d" term can dominate and comparison sorts remain the pragmatic choice.
Explain the roofline model and how you would use it to determine whether a computation (for example, a batched matrix multiply) is compute-bound or memory-bound. Given the FLOP count and the number of bytes moved for an operation, walk through computing its arithmetic intensity and comparing it against a system's roofline.
Sample Answer
Direct answer: The roofline model plots achievable performance (FLOPs/second) against a computation's arithmetic intensity (FLOPs performed per byte of memory moved), with a "roof" formed by two ceilings: a flat ceiling at the hardware's peak compute throughput, and a sloped ceiling determined by peak memory bandwidth. A computation is COMPUTE-BOUND if its arithmetic intensity is high enough to sit under the flat compute ceiling; it's MEMORY-BOUND if its arithmetic intensity is low enough that the sloped memory-bandwidth ceiling is the binding constraint.
Structured elaboration
Arithmetic intensity I=bytes movedFLOPs. The roofline's two ceilings:
Attainable performance=min(Peak FLOPs/s, I×Peak Bandwidth)For low I (few FLOPs per byte moved - e.g. simply summing an array, 1 FLOP per 4-8 bytes read), the I×Bandwidth term is the binding constraint: you're MEMORY-BOUND, and adding more compute capability (a faster chip) won't help until you either increase I (do more work per byte moved, e.g. via tiling/blocking to increase reuse) or increase available bandwidth. For high I (many FLOPs per byte - e.g. a well-tiled matrix multiply, which reuses each loaded value many times), you eventually hit the flat compute ceiling: you're COMPUTE-BOUND, and only a faster compute unit (or lower-precision arithmetic, or fewer redundant FLOPs) helps.
Worked example
The question gives: matrix multiply requires 2n3 FLOPs and moves O(n2) elements of size 4 bytes (assume single-precision floats, and that with sufficient blocking each of the n2 elements per matrix is read from main memory only once, a best-case bandwidth assumption). Arithmetic intensity:
I=3×n2×4 bytes2n3 FLOPs=12n22n3=6n FLOPs/byte(the factor of 3 accounts for reading matrices A and B and writing/reading the output C, each n2 elements). Take a representative GPU with peak compute of 20 TFLOP/s and peak memory bandwidth of 900 GB/s. The ridge point (where the two ceilings cross) is at Iridge=Peak FLOPs/Peak Bandwidth=20×1012/900×109≈22.2 FLOPs/byte. Setting I=n/6=22.2 gives n≈133: for n larger than roughly 133 (with this idealized single-read-per-element assumption), the (well-tiled) matrix multiply is compute-bound; for smaller n, it would be memory-bound. This matches real-world experience: large matrix multiplies are compute-bound on modern accelerators (which is exactly why they benefit so much from more raw FLOP throughput, e.g. specialized tensor cores), while operations with inherently low arithmetic intensity (elementwise ops, simple reductions) remain memory-bound regardless of how fast the compute units are.
Trade-offs & pitfalls
- This calculation assumes an IDEALIZED memory-access pattern (each element read exactly once, via good tiling) - a naive, unblocked matrix multiply has much lower EFFECTIVE arithmetic intensity (repeated re-reads of the same data from memory), which is precisely why tiling (the roofline-adjacent technique from the earlier survivor) matters: it doesn't change FLOP count, but it increases effective arithmetic intensity by improving reuse, potentially shifting an operation from memory-bound to compute-bound.
- The roofline model is a useful FIRST-ORDER diagnostic, not a complete performance predictor - it ignores latency effects, cache-hierarchy nuances (L1 vs L2 vs L3 have different bandwidths), and assumes perfect overlap of compute and memory access, none of which hold exactly in practice.
- Different operations on the SAME hardware can sit on very different points of the roofline - profiling a real workload's actual arithmetic intensity (not just assuming from the algorithm's FLOP formula) is the correct way to diagnose whether a specific kernel is compute- or memory-bound before trying to optimize it.
Unlock Full Question Bank
Get access to all 47 Time and Space Complexity Analysis interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.