Skip to content

Lesson 19 of 27Talk it through

Handling Follow-Up Questions

Answer the stream, memory, scale, space and concurrency follow-ups that turn a correct solution into a strong hire, with a repeatable answer shape.

14 min read0/4 questions

You solved the problem, traced it, and stated the complexity. There are eight minutes left, and the interviewer says: "Nice. Now what if the numbers arrive as a stream and you can't store them all?" This is the part of the round many candidates treat as a cool-down, and it is where a lot of hiring decisions are actually made. The main solve shows you can find an answer. The follow-ups show whether you understand why that answer works, which is what separates "hire" from "strong hire". This lesson gives you an answer shape you can reuse, a catalogue of the follow-ups that come up again and again, and the canonical follow-ups for problems you are likely to see.

Why follow-ups exist

Interviewers ask follow-ups for three reasons, and knowing which one is in play tells you how to answer.

  1. To probe depth. Many candidates have memorised the optimal solution to popular problems. A follow-up changes one assumption, and memorisation stops helping. If you understand which property of the input your algorithm relied on, you can say what breaks and what replaces it.
  2. To fill the rubric. Most structured rubrics have rows for problem solving, coding, verification and communication. The follow-up is the cheapest way for an interviewer to collect evidence of senior-leaning judgement: trade-offs, scale, failure modes.
  3. To use the remaining time. If you finished early, the interviewer has a prepared list. Finishing fast and answering two follow-ups well is a stronger packet than finishing slowly with none.

The practical takeaway: a follow-up is not a trap and not a new problem to solve from scratch. It is usually one changed assumption. Your job is to find which part of your solution depended on that assumption.

The answer shape

Use the same four beats for nearly every follow-up. Say each one out loud.

  1. Restate the change. "So the input no longer fits in memory, but I can read it in order."
  2. Name what breaks. "My solution puts every value in a hash set, which needs all n values in memory. That is the part that fails."
  3. Propose the replacement. "I can keep only the k largest in a min-heap of size k."
  4. Cost and trade-off. "That is O(n log k) time and O(k) memory. The trade-off is I lose the ability to answer for a different k without rereading the stream."

Beat 2 is the one people skip, and it is the one that carries the most signal. It proves you know which line of your code depends on which assumption.

One follow-up, four beats
InterviewerYouWhat if values can be negative?So sums can now drop as the window growsMy shrink step assumed growing only addsPrefix sums plus a monotonic dequeStill O(n), but O(n) extra space

The interviewer changes one assumption of a 'shortest subarray with sum at least k' problem you solved with a sliding window.

1/5
Put it in order4 steps

Put the beats of a good follow-up answer in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

The catalogue

These eight follow-ups cover most of what you will hear after a medium problem. For each, learn the property it attacks and two or three standard replacements.

Follow-upWhat it attacksStandard replacements
"What if the input is a stream?"Random access, a second pass, knowing nOnline algorithms, a heap of size k, running aggregates, reservoir sampling
"What if it doesn't fit in memory?"Holding everything at onceExternal sort, chunking, hash partitioning to disk, map-reduce
"What if this is called a million times?"Paying the full cost per callPrecompute, cache, build an index, move work from query to update
"What if values can be negative?"Monotonic behaviour of sums and pathsPrefix sums instead of windows, Bellman-Ford instead of Dijkstra, track min and max
"Return all answers, not one?"Stopping at the first hitCollect instead of return, output-sensitive complexity, backtracking
"Can you do it in O(1) extra space?"Your hash map or copySort in place, two pointers, reuse the input as storage, bit tricks
"What if it's distributed or concurrent?"One process, one memoryShard by key, merge partial results, locks around compound operations
"How would you test this in production?"Your confidence in unit testsMetrics, sampled checks against a slow reference, property checks, gradual rollout

Streams

A stream means you see each item once, in order, and you do not know how many are coming. Anything that needs len(), indexing, or a second pass is out. The question becomes: what is the smallest summary of the past that still answers the question?

  • A running max, sum or count needs O(1).
  • The top k needs a min-heap of size k: the smallest of the current top k sits on the root, ready to be evicted.
  • A running median needs two heaps, as you saw in Decoding Backtracking and Heaps.
  • A fair random sample of k items needs reservoir sampling: keep the first k, then replace a random slot with item i with probability k / (i + 1).
Pythonstreams.py
import heapqimport random def top_k_stream(stream, k): """Keep the k largest values seen so far. O(k) memory, O(log k) per value.""" heap = [] for x in stream: if len(heap) < k: heapq.heappush(heap, x) elif x > heap[0]: heapq.heapreplace(heap, x) # pop the smallest, push x return sorted(heap, reverse=True) def reservoir_sample(stream, k, rng): """Pick k items uniformly from a stream of unknown length in one pass.""" sample = [] for i, x in enumerate(stream): if i < k: sample.append(x) else: j = rng.randrange(i + 1) # 0..i inclusive if j < k: sample[j] = x return sample # The stream is a generator: no len(), no second pass, no indexing.def readings(n): for i in range(n): yield (i * 7919) % 10_007 expected = sorted(readings(10_000), reverse=True)[:3] # the O(n) memory wayassert top_k_stream(readings(10_000), 3) == expectedassert top_k_stream(iter([4, 1]), 3) == [4, 1] # Fairness check: each of 10 items should be picked about k/n = 30% of the time.rng = random.Random(42)counts = [0] * 10trials = 20_000for _ in range(trials): for x in reservoir_sample(iter(range(10)), 3, rng): counts[x] += 1rates = [c / trials for c in counts]assert all(abs(r - 0.3) < 0.02 for r in rates), ratesprint("top 3:", top_k_stream(readings(10_000), 3))print("pick rates:", [round(r, 2) for r in rates])
Output
Press Run (⌘ Enter) to see what happens.

Notice that the test compares the streaming answer against the obvious O(n) memory version. That is the same brute-force-as-reference habit from Brute Force First, and it is worth mentioning when you propose a streaming change: "I would check it against the sort-everything version on small inputs."

Predict the outputPython

What does this print?

import heapq
h = []
for x in [5, 1, 9, 3, 7]:
  heapq.heappush(h, x)
  if len(h) > 3:
      heapq.heappop(h)
print(h[0], len(h))
Need a nudge? Hints walk you through it.

Too big for memory

When the data is larger than RAM, the answer is almost always split, process each piece, combine. The details depend on whether pieces can be combined.

  • Sorting: sort chunks that fit in memory, write each sorted run to disk, then do a k-way merge with a heap of run heads. That is external merge sort, and it is what databases do when a sort spills.
  • Counting or grouping: hash each key to one of, say, 100 files. Every occurrence of a key lands in the same file, so each file can be counted on its own. This is the shuffle step of map-reduce.
  • Approximate is acceptable: a fixed-size sketch (such as a count-min sketch for frequencies or HyperLogLog for distinct counts) trades exactness for tiny memory. Only offer this if you can say what error it introduces.

The senior detail is that the partition key decides correctness. "Top 10 most frequent words across 100 machines" can be answered by taking each machine's local top 10 and merging, but only if the data was partitioned by word. If the same word is spread across machines, a word that is 11th everywhere can be 1st overall, and the local top 10s miss it.

Called a million times

This follow-up asks you to move work from query time to setup or update time. Name the ratio of reads to writes, because it decides the design.

Pythontwo_sum_class.py
from collections import Counter class TwoSumFastAdd: """add O(1), find O(n). Good when writes dominate.""" def __init__(self): self.counts = Counter() def add(self, x: int) -> None: self.counts[x] += 1 def find(self, target: int) -> bool: for x, c in self.counts.items(): y = target - x if y != x and y in self.counts: return True if y == x and c >= 2: return True return False class TwoSumFastFind: """add O(n), find O(1). Good when reads dominate.""" def __init__(self): self.nums = [] self.sums = set() def add(self, x: int) -> None: for y in self.nums: self.sums.add(x + y) self.nums.append(x) def find(self, target: int) -> bool: return target in self.sums for cls in (TwoSumFastAdd, TwoSumFastFind): ts = cls() for x in (1, 3, 5): ts.add(x) assert ts.find(4) and ts.find(8) assert not ts.find(2) # 1 + 1 needs two 1s ts.add(1) assert ts.find(2) # now it has two 1s print(cls.__name__, "ok")
Output
Press Run (⌘ Enter) to see what happens.

Neither class is "the right one". The fast-find version also stores up to n² sums, which matters at a million values. The model sentence is: "It depends on the ratio. If adds and finds are about equal, I keep the counter, because O(n²) memory is a worse risk than O(n) finds." Other standard moves here: prefix sums for repeated range queries, functools.cache for repeated pure calls, a sorted array plus binary search for repeated lookups by range, and a precomputed index such as anagram signature to group.

Negatives, all answers, O(1) space

  • Negatives break anything that relies on "adding makes it bigger". Sliding windows on sums become prefix sums with a hash map (Decoding Arrays and Strings). Dijkstra becomes Bellman-Ford. Maximum product subarray needs the running minimum as well as the maximum, because a negative times a negative flips.
  • All answers changes the complexity to depend on the output. If there can be O(n²) valid pairs, no algorithm lists them faster than O(n²). Say so: "The output itself can be quadratic, so my time is O(n + output)."
  • O(1) space usually means one of four things: sort in place and use two pointers, overwrite the input (mark seen values by negating nums[v - 1] when values are 1 to n), use a cycle trick (Floyd's tortoise and hare on Find the Duplicate Number), or use XOR. Ask whether mutating the input is allowed, and remember that recursion depth counts as space.

Distributed, concurrent, and in production

  • Concurrent: find the compound operations. In an LRU cache, get is not a read, because it moves the key to the front. So a reader-writer lock does not help, and the simple correct answer is one lock around both get and put. To scale, shard into N independent caches by hash(key) % N, each with its own lock. Say the trade-off: eviction is now per shard, so it is only approximately least recently used overall.
  • Distributed: shard by the key the question groups by, compute local results, and merge. Then name the failure modes you would have to handle, such as a slow shard or an uneven key.
  • Testing in production: log inputs and outputs for a sample, rerun the sample against the slow brute-force reference offline, add property checks (output sorted, sum preserved), watch latency percentiles, and roll out behind a flag to a small percentage first.
Match the pairs0/6 matched

Match each follow-up to the property of the original solution it attacks.

Choose an item, then its match on the other side.

Canonical follow-ups for common problems

Interviewers reuse the same extensions for the same problems. Know these before you walk in.

ProblemLikely follow-upShort model answer
Two Sum"The array is sorted." / "Design a class with add and find."Two pointers, O(1) space. For the class, pick by read and write ratio (above).
Top K Frequent"The words stream in."Counter plus a size-k heap, rebuilt or updated per batch; exact counts need memory per distinct word, so mention a sketch if that is too much.
Kth Largest"Values keep arriving, answer after each."Keep a min-heap of size k; the root is the answer at every step.
LRU Cache"Make it thread-safe."One lock around get and put, because get mutates order. Shard for throughput, accept approximate LRU.
Merge Intervals"Intervals arrive one at a time."Keep a sorted structure of disjoint intervals and merge each new one with its overlapping neighbours, O(log n) to find plus the merges.
Number of Islands"Land is added cell by cell, report the count each time."Union-find over cells; each addition is near O(1) amortised with path compression and union by rank.
Longest Consecutive Sequence"Values arrive one at a time."Map run endpoints to lengths and merge neighbours, as covered at the end of The Full Walkthrough.
Valid Parentheses"Only one bracket type, O(1) space."A counter replaces the stack; fail if it ever goes negative.
Quick check
You computed 'top 10 most frequent search terms' on one machine. The interviewer asks how to do it across 50 machines, each holding a random slice of the logs. Which plan is correct?
Need a nudge? A hint rules out a wrong answer.

When the honest answer is "it depends"

"It depends" is a strong answer only when you finish the sentence. Name the variable, then give the answer for each side.

  • "It depends on the read and write ratio. Read-heavy, I precompute. Write-heavy, I compute on query."
  • "It depends on whether I can mutate the input. If yes, sort in place for O(1) space. If not, a hash set."
  • "It depends on whether approximate is acceptable. For a dashboard, a sketch is fine. For billing, it has to be exact."

When you genuinely do not know a technique, reason from the beat that matters most: what breaks. "I have not used a structure for this, but the problem is that I cannot keep all counts. So I need a summary smaller than the data, and I need to know how wrong it can be." That reasoning earns credit even without a name to attach to it.

Key terms
follow-up
A variation asked after the main solve that changes one assumption to test whether you understand why your solution works.
online algorithm
An algorithm that processes input one item at a time, in order, without seeing the future or storing everything.
reservoir sampling
Choosing k items uniformly at random from a stream of unknown length in one pass, using O(k) memory.
external merge sort
Sorting data larger than memory by sorting chunks, writing them to disk as runs, and k-way merging the runs.
hash partitioning
Sending each record to a bucket chosen by hashing its key, so all records for a key end up together.
output-sensitive
A complexity that depends on the size of the answer, such as O(n + k) when k results must be listed.
sharding
Splitting data or work across independent pieces by key so each can be handled separately.