Scaling a Solved Algorithm When the Data Outgrows Memory
System DesignModel answerLast updated
Explain how to adapt a working in-memory solution when the input becomes far too large, moving from constraints to streaming, external sorting, approximation or distribution.
You have just finished a correct, in-memory solution to a typical algorithm problem, such as merging intervals, counting or grouping records, or sorting. The interviewer then asks:
"Suppose the input were enormous. What would you change?"
Write the answer a strong candidate would give. It should be a structured way of reasoning from the constraints to a design, not a list of buzzwords.
Your answer should:
- Name the clarifying questions you would ask first, and explain why each one changes the design.
- Walk through the main strategies in a sensible order of escalation: tightening the in-memory solution, streaming, chunk-and-merge, external-memory techniques, approximation, and finally distribution across machines.
- Say when each strategy applies and what it costs in correctness, memory, I/O, latency and complexity.
- Show how the approach works on at least one concrete example, such as interval merging or top-k frequent items.
- Avoid jumping to "use a distributed system" without first justifying why a single machine is not enough.
Hints
Hint 1
Start by quantifying: how many bytes is the input, how much memory do you have, and is the data static, streamed or changing? The answer decides which strategy is even needed.
Hint 2
Ask what the output actually needs. If it is a small summary (a count, a max, top-k), compact running state may be enough. If it needs a global ordering, you need sorting or an index.
Hint 3
Order your options by escalation: better in-memory layout, one-pass streaming, chunk and merge, external sort, approximate sketches, and only then multi-machine partitioning. Mention the cost of each step up.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Start with constraints, not techniques
I would not answer with a technology. I would first ask questions that determine which strategy is justified.
- Size versus memory: Does the data fit in RAM? Roughly how big is it, and what is the memory budget? 100 million 8-byte integers is about 800 MB and may still fit. 100 billion records does not.
- Data shape: Is it a static file, a stream, or continuously updated?
- Output: Do we need a small summary (count, sum, top-k) or a full, globally ordered result?
- Exactness: Is an approximate answer acceptable, and with what error bound?
- Bottleneck: Is the limit memory, disk I/O, network, latency or throughput?
- Deployment: Single machine or a cluster available?
Each answer removes options, which is why I ask before designing.
Escalation ladder
1. Make the in-memory solution cheaper
If the data almost fits, try this first. Use compact types (32-bit instead of 64-bit, arrays instead of objects), drop fields you do not need, intern repeated strings, or memory-map the file. This is the cheapest change and adds no new failure modes.
2. Streaming (single pass, small state)
If the answer is a summary, read records one at a time and keep only compact state.
- Count, sum, min, max, mean: O(1) state.
- Top-k frequent with a bounded key set: hash map plus a heap of size k.
- Sample uniformly: reservoir sampling, O(k) memory.
Memory becomes independent of input size. The limit is that the problem must be decomposable into a running state. Exact distinct counts or exact medians generally are not.
3. Chunk and merge
If the problem decomposes, process pieces independently and combine partial results.
Example, merging intervals: sort each chunk that fits in memory, merge intervals within the chunk, write the result, then merge the chunk outputs. Merged intervals are usually far fewer than raw ones, so the second stage is often small.
Requirement: the combine step must be associative (sums, maxima, set union, merged intervals). That also makes it parallel-friendly.
4. External-memory algorithms
If you need global order or coordination across all data, use disk deliberately.
External merge sort:
- Read chunks that fit in memory (say 1 GB), sort each, write as a sorted run.
- Do a k-way merge of the runs with a min-heap, reading each run through a buffer.
Cost: O(N log N) comparisons, but I/O is about two passes over the data if the number of runs fits a single merge (runs ≤ memory / buffer size). With 1 TB data and 1 GB memory, that is about 1000 runs, which a single 1000-way merge handles with about 1 MB buffers.
After sorting, many problems become one linear scan with O(1) memory. For intervals, sort by start, then merge in one pass. For grouping, sorted data puts equal keys adjacent.
Alternatives: hash partitioning to disk (all records with the same key land in the same bucket, then process each bucket in memory), or disk-backed indexes such as B-trees or LSM trees when you need repeated lookups.
5. Approximation
If the exact answer is too expensive and error is tolerable, use sketches with known bounds.
- Distinct count: HyperLogLog (KBs of memory, about 1-2% error).
- Frequency estimates and heavy hitters: Count-Min Sketch, Misra-Gries.
- Membership: Bloom filter (no false negatives, tunable false-positive rate).
- Quantiles: t-digest or GK sketch.
Always state the guarantee and confirm with the interviewer that approximation is acceptable. Sketches are also mergeable, which helps distribution.
6. Distribute across machines
Only when a single machine's disk, I/O bandwidth or time budget is insufficient.
- Partition by key (hash) so each key lives on one worker, or by range to preserve order.
- Map-reduce shape: local aggregation first (combiners) to cut network traffic, then shuffle, then reduce.
- Concerns: data skew (hot keys), stragglers, retries and idempotency, shuffle cost, and exactly-once versus at-least-once semantics.
A distributed system adds operational complexity and network cost. I would justify it with numbers: for example, scanning 10 TB at 200 MB/s on one disk takes about 14 hours, while 100 workers bring it to minutes.
Worked example: top-k frequent items
- Fits in memory: hash map plus heap, O(N) time.
- Too many distinct keys for memory but a single machine: hash-partition records into P files by key, count each partition in memory, keep a size-k heap across partitions. Exact result.
- Streaming, approximate OK: Count-Min Sketch plus a heap of candidates, or Misra-Gries.
- Cluster: each worker computes a local top counts per key partition, and since keys are partitioned, the global top-k is the merge of per-worker top-k lists. If partitioned by record instead of key, local top-k is not sufficient and you need full counts or sketches.
Trade-offs to state explicitly
| Choice | Gains | Costs |
|---|---|---|
| Streaming | Tiny memory | Limited problem types |
| External sort | Exact, global order | Disk I/O, more passes |
| Sketches | Very small, mergeable | Approximate, tuning |
| Distribution | Throughput, capacity | Complexity, network, skew, failures |
Common mistakes
- Saying "use Hadoop/Spark" immediately, without sizing the problem.
- Ignoring that the combine step must be correct (for example, averaging averages instead of keeping sum and count).
- Forgetting skew: one hot key can overwhelm a single worker.
- Proposing approximations without asking whether exact results are required.
- Ignoring I/O cost: an O(N log N) algorithm with random disk access can be far slower than a sequential multi-pass one.
- Not discussing how the original algorithm's complexity changes (time, memory, passes).
Closing summary
I would say: "First I would quantify the size and ask what output is required. If it fits with tighter data structures, I stop there. If only a summary is needed, I stream. If the problem decomposes, I chunk and merge. If I need global order, I use external sort. If exactness is negotiable, I use sketches. Only when one machine cannot meet the throughput or storage need do I partition across a cluster, and then I design for skew and failure."