Recursion Depth Exceeded
Problem
A catalogue service keeps a map of deprecated product SKUs to the SKU that replaced them. Because products are replaced repeatedly, resolving a SKU means following the chain until it reaches one that is still current:
def resolve_sku(sku: str, replaced_by: dict[str, str]) -> str:
"""Follow the replacement chain until we reach a SKU that is still current."""
if sku not in replaced_by:
return sku
return resolve_sku(replaced_by[sku], replaced_by)Symptom: the nightly job that resolves every SKU in the catalogue has been fine for two years and now dies with RecursionError: maximum recursion depth exceeded on one product family. A separate, much rarer report is a job that dies with the same error on a SKU with only three known replacements. Explain both failures and fix the function.
Examples
replaced_by = {"A1": "A2", "A2": "A3"},resolve_sku("A1")→"A3". Fine.- A family with 1,400 successive replacements (weekly revisions over many years) →
RecursionErrorat around depth 1,000, the default CPython recursion limit. Expected: the current SKU. replaced_by = {"B1": "B2", "B2": "B3", "B3": "B1"}(a data-entry loop) →RecursionErrorafter roughly 1,000 calls. Expected: a clear error such asValueError: replacement cycle at B1, not a crash that looks like the long-chain case.
Hints
- How deep can the call stack go before CPython refuses to grow it?
sys.getrecursionlimit()tells you. - Each recursive call here does no work after the callee returns. What does that tell you about whether the stack is needed at all?
- The three-SKU failure is not about depth. Trace it by hand.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.