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.
Given the following sample performance counters collected from a run: cycles=1,200,000,000; instructions=2,400,000,000; L1-dcache-load-misses=50,000; branch-misses=10,000. Estimate CPI (cycles per instruction), comment on whether the program is CPU- or memory-bound, and recommend two focused optimizations based on these counters.
Sample Answer
Direct answer
CPI (cycles per instruction) here is 0.5, which means the CPU is retiring roughly 2
instructions per cycle. Combined with L1 data-cache and branch miss rates that are both
under 0.03 misses per 1,000 instructions, this run is CPU-bound with excellent memory
behavior, not memory-bound: the bottleneck is the volume and shape of the work itself,
not stalls waiting on cache lines or mispredicted branches.
Structured elaboration
CPI=instructionscycles,IPC=CPI1CPI below 1 (equivalently IPC above 1) is only possible on a superscalar core that can
retire multiple instructions per cycle, so a CPI of 0.5 already tells you the workload
is exploiting instruction-level parallelism reasonably well, not stalling constantly.
To judge whether misses are actually significant, normalize by instruction count using
misses per kilo-instruction (MPKI), not the raw counts:
A memory-bound program typically shows CPI well above 1 alongside double-digit MPKI
(many stalled cycles waiting on cache lines); a program with low MPKI and low CPI is
compute-bound: the pipeline is mostly busy doing arithmetic and control flow, not
waiting.
This same reasoning applies unchanged whether the four counters came from a live
perf stat capture during a production latency regression, or from microbenchmarking
an isolated numerical kernel like a matrix multiply: CPI and MPKI are dimensionless
ratios, so the diagnostic logic transfers directly regardless of where the counters
were collected.
Worked example
CPI=2,400,000,0001,200,000,000=0.5,IPC=2.0 L1-dcache MPKI=2,400,000,000/100050,000=2,400,00050,000≈0.021 branch-miss MPKI=2,400,00010,000≈0.004An L1-dcache MPKI of about 0.02 and a branch-miss MPKI of about 0.004 are both very
low; a genuinely memory-bound loop routinely shows MPKI in the tens. Together with a
CPI of 0.5 (IPC of 2), the counters point at a tight, cache-friendly, well-predicted
piece of code where the CPU's execution units, not its memory subsystem, are the limit.
Two focused optimizations, given this profile:
- Vectorize the hot loop (SIMD). Since the core is already achieving good IPC and
is not memory-stalled, the highest-leverage change is doing more useful work per
cycle, not removing stalls that barely exist. Rewriting the innermost arithmetic to
use SIMD instructions (AVX2/AVX-512, or the compiler's auto-vectorizer with the
right flags and data layout) processes multiple data elements per instruction,
directly cutting the instruction count for the same amount of work. - Reduce algorithmic/instruction-count overhead, not memory access patterns:
look for redundant bounds checks, avoidable function-call overhead, or repeated
recomputation inside the hot path (strength reduction, hoisting invariants out of
loops, loop fusion). Because the cache and branch predictor are already behaving
well, restructuring data layout for locality (a common first instinct) would not
move the needle here; cutting the number of instructions executed would.
Trade-offs & pitfalls
CPI alone can be misleading without the miss-rate context, though not in the direction
people usually reach for. Wasted speculation cannot explain a LOW CPI: the instructions
counter records RETIRED instructions, so work that is executed speculatively and then
squashed burns cycles without ever incrementing the denominator, which pushes CPI UP, not
down. A CPI of 0.5 alongside a high MPKI means one of two things instead, and they call
for different fixes. Either the out-of-order engine is successfully overlapping those
misses, with many independent misses in flight at once, which is genuinely efficient and
says the memory system is not the limit despite the miss count; or the instruction stream
is padded with cheap, fast-retiring work (redundant bounds checks, bookkeeping, a bloated
inner loop) that inflates the instruction count and therefore DILUTES MPKI without doing
anything useful, in which case the instruction count itself is the problem and the low
miss rate is a red herring. Telling those two apart needs a counter that CPI and MPKI do
not contain: stall cycles attributable to the memory subsystem, or a top-down breakdown
of every issue slot into retiring, bad speculation, front-end bound and back-end bound.
Always read CPI together with MPKI, never CPI in isolation, and read both together with
where the cycles are actually going. It is also easy to over-read a handful of aggregate counters from a single
run: a short or non-representative sampling window can understate rare but expensive
stalls (a cold-cache first pass, or a periodic garbage-collection pause) that would
change the diagnosis; where possible, confirm with a longer capture or multiple runs
before committing to an optimization direction.
Implement reservoir sampling (Algorithm R) in Python to sample k items uniformly at random from a stream of unknown length. Provide the function signature: def reservoir_sample(stream_iter, k): -> list. Explain time and space complexity and discuss how this algorithm can be used for log sampling in production pipelines.
Sample Answer
Approach
Algorithm R keeps the first k items unconditionally, then for each subsequent item at 0-indexed position i (i >= k), draws a uniformly random integer j in [0, i]; if j < k, it replaces reservoir[j] with the new item, otherwise the new item is discarded. This gives every item seen so far an equal probability of ending up in the final k-sized sample, without ever needing to know the stream's total length in advance.
Code
import random
def reservoir_sample(stream_iter, k: int) -> list:
reservoir = []
for i, item in enumerate(stream_iter):
if i < k:
reservoir.append(item)
else:
j = random.randint(0, i)
if j < k:
reservoir[j] = item
return reservoir
random.seed(0)
stream = list(range(1, 21))
sample = reservoir_sample(iter(stream), k=5)
print("stream:", stream)
print("sample of 5:", sample)
from collections import Counter
n_items, k, trials = 10, 3, 200_000
counts = Counter()
random.seed(123)
for _ in range(trials):
counts.update(reservoir_sample(iter(range(n_items)), k))
print(f"empirical inclusion probability over {trials:,} trials (expect ~{k/n_items:.3f} each):")
for item in range(n_items):
print(f" item {item}: {counts[item]/trials:.4f}")
Output when run unchanged:
stream: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
sample of 5: [9, 2, 3, 6, 10]
empirical inclusion probability over 200,000 trials (expect ~0.300 each):
item 0: 0.2992
item 1: 0.3010
item 2: 0.3002
item 3: 0.3002
item 4: 0.3010
item 5: 0.2982
item 6: 0.3003
item 7: 0.2995
item 8: 0.3007
item 9: 0.2999
Key points
Every one of the 10 items lands in the size-3 sample close to 30% of the time across 200,000 trials, matching the theoretical k/n = 3/10 = 0.30 inclusion probability, which is the property the algorithm guarantees for every item, not just the ones seen first or last. The randomness has to be drawn fresh once per item after the first k, so the per-item cost is O(1) but not zero.
Complexity
Time: O(1) per stream item after the initial k are collected, so O(N) total for a stream of N items, with only ONE pass and no need to know N in advance. Space: O(k), fixed regardless of stream length.
Edge cases
If the stream has fewer than k items total, the reservoir simply ends up holding all of them, with no error. A k=0 reservoir stays empty throughout. Because each item needs an independent random draw, running this in multiple threads against shared stream state requires either a single-writer design or a thread-safe random source, since correlated or shared random state across threads can silently break the uniformity the algorithm otherwise guarantees.
Production framing
This is a common pattern for log sampling in production pipelines: you want a small, representative, uniform sample of an effectively unbounded log stream for debugging or metrics, without buffering the whole log or running a two-pass algorithm that would need to know the total count first. A single pass with O(k) memory makes it safe to run inline on a live, high-volume stream.
Implement a fixed-capacity LRU cache in Java that supports get(key) and put(key, value) in O(1) time. Provide class and method signatures, a brief implementation outline, and explain how your design guarantees O(1) operations and how you would make it safe for concurrent access.
Sample Answer
Direct answer
An LRU (least-recently-used) cache gets O(1) get and put by combining a hash map (for O(1) key lookup) with a doubly linked list (for O(1) reordering and eviction): the map finds a node instantly, and the linked list lets you move that node to the front or drop the tail in constant time without shifting anything.
Structured elaboration
Class and method signatures:
public class LRUCache {
public LRUCache(int capacity) { ... }
public int get(int key) { ... } // returns value, or -1 if absent
public void put(int key, int value) { ... }
}
Design: keep a Map<Integer, Node> for O(1) lookup from key to its node, and a doubly linked list of nodes ordered from most-recently-used (head) to least-recently-used (tail), using two dummy sentinel nodes (head and tail) so every real node always has a real prev and next, removing edge-case checks for "is this the first/last node."
get(key): look up the node in the map (O(1)); if found, unlink it from its current position and re-insert it right after the head sentinel (O(1) pointer updates), then return its value; if absent, return -1.put(key, value): if the key already exists, update its value and move it to the front the same way asget. If it's new and the map is already at capacity, remove the node just before the tail sentinel (the true least-recently-used entry) from both the list and the map (O(1)), then insert the new node right after the head sentinel and add it to the map (O(1)).
Every one of these steps touches a fixed, small number of pointers or one hash map operation, none of it scales with the number of entries currently cached, which is exactly what makes both operations O(1).
Concurrent access: the map-plus-linked-list structure above is NOT thread-safe as written, because get mutates the list (moving a node) even though it looks like a read, so two threads calling get concurrently can corrupt the linked list's pointers. The simplest correct fix is a single lock (e.g., a ReentrantLock or synchronized block) wrapping both get and put in their entirety; this sacrifices true parallelism (only one thread touches the cache at a time) but is simple and correct, and is often good enough because LRU-cache operations are already O(1) and fast, so lock contention is usually brief. For higher concurrency, options include: sharding the cache into N independent LRU caches keyed by hash(key) % N, each with its own lock, so unrelated keys don't contend; or using ConcurrentHashMap for the map alongside a separate lock scoped only to the linked-list mutation, being careful that get's "read" is actually a "read plus reorder" and must be protected the same as put. A lock-free doubly linked list is possible in principle but is a substantial correctness hazard to hand-roll and is rarely worth it compared to sharding for this specific use case.
Worked example
import java.util.HashMap;
import java.util.Map;
public class LRUCache {
private static class Node {
int key, value;
Node prev, next;
Node(int key, int value) { this.key = key; this.value = value; }
}
private final int capacity;
private final Map<Integer, Node> map = new HashMap<>();
private final Node head = new Node(-1, -1);
private final Node tail = new Node(-1, -1);
public LRUCache(int capacity) {
this.capacity = capacity;
head.next = tail;
tail.prev = head;
}
public int get(int key) {
Node node = map.get(key);
if (node == null) return -1;
moveToFront(node);
return node.value;
}
public void put(int key, int value) {
Node node = map.get(key);
if (node != null) {
node.value = value;
moveToFront(node);
return;
}
if (map.size() == capacity) {
Node lru = tail.prev;
removeNode(lru);
map.remove(lru.key);
}
Node fresh = new Node(key, value);
map.put(key, fresh);
addToFront(fresh);
}
private void addToFront(Node node) {
node.prev = head;
node.next = head.next;
head.next.prev = node;
head.next = node;
}
private void removeNode(Node node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}
private void moveToFront(Node node) {
removeNode(node);
addToFront(node);
}
public static void main(String[] args) {
LRUCache cache = new LRUCache(2);
cache.put(1, 100);
cache.put(2, 200);
System.out.println("get(1) -> " + cache.get(1));
cache.put(3, 300);
System.out.println("get(2) -> " + cache.get(2));
System.out.println("get(3) -> " + cache.get(3));
cache.put(4, 400);
System.out.println("get(1) -> " + cache.get(1));
System.out.println("get(3) -> " + cache.get(3));
System.out.println("get(4) -> " + cache.get(4));
}
}
Save this as LRUCache.java (the two java.util imports at the top are required; without them javac fails with cannot find symbol: class Map and cannot find symbol: class HashMap, since Map and HashMap are not in the implicitly-imported java.lang package). Compiled with javac LRUCache.java and run with java LRUCache on JDK 17, this prints:
get(1) -> 100
get(2) -> -1
get(3) -> 300
get(1) -> -1
get(3) -> 300
get(4) -> 400
Tracing why: capacity is 2. After put(1,100) and put(2,200), both are cached. get(1) returns 100 and makes 1 the most-recently-used, so 2 is now the least-recently-used. put(3,300) needs to evict since the cache is full, so it evicts key 2, confirmed by get(2) returning -1. get(3) correctly returns 300. put(4,400) evicts the current least-recently-used, which is now key 1 (since 3 was just used), confirmed by get(1) returning -1 while get(3) and get(4) both still return their values.
Trade-offs and pitfalls
One more detail worth carrying from the listing above: map.size() == capacity is the eviction test rather than >=, which is safe here only because eviction happens before every insert so the map can never exceed capacity; if a later change ever inserted without evicting first, == would silently stop evicting and the cache would grow without bound, so >= is the more defensive test. A common mistake is using a singly linked list or skipping the sentinel head/tail nodes, which forces special-case handling for the first and last real node and is a frequent source of off-by-one pointer bugs. Another is implementing get as a pure read without moving the accessed node to the front, which silently breaks the LRU property (the cache degrades into an arbitrary eviction policy) without throwing any error. In Python, the same guarantees come essentially for free from collections.OrderedDict (move-to-end on access, pop the first item to evict) or from functools.lru_cache as a decorator when the cache wraps a pure function rather than arbitrary key/value pairs; those built-ins hide the doubly-linked-list-plus-hashmap machinery described above rather than removing the need for it.
Given this C-like loop, estimate the instruction count and cycles per element, and suggest how to vectorize it using SIMD intrinsics:
for (int i = 0; i < n; ++i) {
y[i] = a * x[i] + b;
}
Describe assumptions about compiler optimizations and memory alignment.
Sample Answer
Approach. The loop y[i] = a * x[i] + b does one multiply and one add per element, both independent across iterations (no loop-carried dependency), which makes it a textbook target for SIMD (Single Instruction, Multiple Data: one instruction that applies the same operation to several data elements at once) vectorization: a fused multiply-add over a small vector of elements replaces several scalar multiply-add instructions.
Estimating scalar cost. With no vectorization, a compiler with -O2 typically emits one load, one multiply, one add (or a fused multiply-add), and one store per element, roughly 3-4 instructions per element. On a modern superscalar core these are independent across iterations, so with good pipelining the throughput-limited cost is close to 1 element per cycle, though this loop reads 4 bytes and writes 4 bytes per element for only 2 FLOPs
(floating-point operations: one multiply and one add), giving very low arithmetic intensity (about 2 FLOPs per 8 bytes moved), so on most hardware this kernel is memory-bandwidth-bound rather than compute-bound even before vectorizing.
Vectorized code (NEON; the same idea in x86 SIMD uses <immintrin.h> with __m256/_mm256_fmadd_ps).
#include <arm_neon.h>
void axpb_simd(const float* x, float* y, float a, float b, int n) {
float32x4_t va = vdupq_n_f32(a);
float32x4_t vb = vdupq_n_f32(b);
int i = 0;
for (; i + 4 <= n; i += 4) {
float32x4_t vx = vld1q_f32(x + i);
float32x4_t vy = vfmaq_f32(vb, va, vx); // vy = vb + va*vx, 4 lanes at once
vst1q_f32(y + i, vy);
}
for (; i < n; ++i) // remainder: n not a multiple of the vector width
y[i] = a * x[i] + b;
}
Run against a scalar baseline on n = 4099 (deliberately not a multiple of 4, to exercise the remainder loop) with pinned data (srand(7)):
n=4099, sample x[0..3]=64.90 -25.70 -72.40 -33.50
scalar y[0..3]=161.2500 -65.2500 -182.0000 -84.7500
simd y[0..3]=161.2500 -65.2500 -182.0000 -84.7500
max |scalar - simd| over all 4099 elements = 0.000000
results match: true
Key points. One vfmaq_f32 replaces 4 scalar multiply-add pairs, cutting instruction count roughly 4x for the vectorizable part of the loop; this assumes x and y are reasonably aligned (misaligned loads/stores can cost extra cycles on some architectures) and that the compiler either auto-vectorizes with -O2/-O3 plus target flags, or the intrinsics are written by hand as above when auto-vectorization does not trigger (common when pointers might alias, hence a real implementation would mark them restrict).
Complexity. Both versions are O(n) time and O(1) extra space; vectorization changes the constant factor (instructions issued per element), not the asymptotic class.
Edge cases. n not a multiple of the vector width (handled by the scalar remainder loop above); unaligned x/y pointers; and the case where instruction-count reduction does not translate into proportional wall-clock speedup because the kernel is memory-bandwidth-bound, in which case widening the vector further mostly waits on the same memory bus rather than doing useful extra work.
You have two algorithms: one is O(N log N) and the other is O(N). For N = 1e6, assume each arithmetic operation on CPU costs 5 ns and a memory access that misses the cache costs 100 ns. Describe how you would estimate practical runtimes for each algorithm accounting for memory access patterns and cache miss rates (e.g., 1% vs 10%), and explain under what realistic conditions the O(N log N) algorithm could be faster than the O(N) algorithm.
Sample Answer
Direct answer. Big-O complexity describes how operation count scales, but wall-clock time also depends on the cost per operation, which memory access patterns change dramatically: an algorithm that touches memory unpredictably (scattered, pointer-chasing access) pays a cache-miss penalty on nearly every access, while one with sequential, predictable access mostly hits cache. With a large enough gap in per-operation cost, an asymptotically "worse" O(NlogN) algorithm can beat an asymptotically "better" O(N) one in practice.
Structured elaboration: building the estimate. Model each algorithm's time as (number of memory accesses per element) times (base op cost plus miss-rate-weighted miss cost):
TimeO(N)=N⋅a⋅(top+ma⋅tmiss),TimeO(NlogN)=Nlog2N⋅b⋅(top+mb⋅tmiss)where a,b are memory accesses per element for each algorithm and ma,mb are their respective cache-miss rates.
First, the miss rates the question suggests. Plug in N=106, top=5ns, tmiss=100ns, a=3, b=1, and the two rates named in the question, 10% for the scattered linear algorithm and 1% for the sequential log-factor one:
TimeO(N)=106×3×(5+0.10×100)ns=45ms,TimeO(NlogN)=106×19.93×(5+0.01×100)ns≈120msAt those rates there is no crossover at all: the linear algorithm still wins by about 2.7x. That is the first thing worth saying out loud, because it sets the bar for what "realistic conditions" has to mean. A log2106≈19.93 factor is a 20x handicap, and a 10% miss rate only triples the linear algorithm's per-access cost (from 5ns to 15ns). Tripling does not cover 20x.
The break-even miss rate. Solve for the ma at which the two are equal, holding mb=0.01, a=3, b=1:
3(5+100ma)=19.93×6=119.58⇒5+100ma=39.86⇒ma≈0.35So the linear algorithm has to miss cache on roughly 35% or more of its accesses before the log-factor algorithm catches it, given three accesses per element against one. That single number is the actual answer to "under what conditions", and it is far outside the 1%-to-10% band the question offers, which is why the crossover needs a genuinely pathological access pattern rather than a merely mediocre one.
Worked example at a rate that does cross over. Suppose the O(N) algorithm is implemented with pointer-chasing (e.g. a linked structure like a chained hash table with poor locality), needing a=3 memory accesses per element at a high ma=0.95 miss rate (scattered heap allocations rarely share a cache line, so almost every access is a fresh line):
TimeO(N)=106×3×(5+0.95×100)ns=106×3×100ns=3×108ns=300msMeanwhile the O(NlogN) algorithm is a comparison-based sort over a contiguous array (e.g. mergesort), doing log2(106)≈19.93 comparisons per element with b=1 access per comparison and a low mb=0.01 miss rate (sequential scans prefetch well):
TimeO(NlogN)=106×19.93×(5+0.01×100)ns=106×19.93×6ns≈120msUnder these assumptions the O(NlogN) algorithm (about 120 ms) beats the O(N) algorithm (about 300 ms) by roughly 2.5x, purely because its per-access cost is so much lower. Note that ma=0.95 is well past the 0.35 break-even derived above, which is the point: the crossover exists, but it lives in the pathological corner of the parameter space, not in the ordinary one.
Trade-offs & pitfalls: the realistic conditions for this crossover. This happens specifically when the O(N) algorithm's constant factor combines a higher access count per element AND a much higher miss rate than the O(NlogN) alternative, typically because the linear algorithm relies on scattered, pointer-heavy structures (hash tables with chaining, trees with heap-allocated nodes) while the log-factor algorithm operates on contiguous, cache-friendly memory. The crossover shrinks or disappears if the O(N) algorithm is instead implemented cache-consciously (e.g. open-addressing with a compact array, low load factor, few probes), which is exactly why "asymptotically better" implementations still lose to careful engineering of the "asymptotically worse" one only under specific memory-layout conditions, not as a general rule.
Two limits of the model are worth stating when you present it. First, it charges the full tmiss for every miss, which overstates the cost of the sequential algorithm: a prefetcher and multiple outstanding misses overlap latency, so a stream of predictable misses costs far less than their sum. That bias makes the model conservative in favour of the linear algorithm, so a crossover the model predicts is more likely to be real than one it rules out. Second, the break-even ma≈0.35 moves with a and b: at a=1 instead of 3, the required rate exceeds 100% and no crossover is possible at these constants at all, so the access count per element matters as much as the miss rate does.
Unlock Full Question Bank
Get access to all 49 Algorithmic Complexity & Code-Level Optimization interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.