Recursion & Backtracking
Recursive thinking as its own subject: how recursive calls actually execute, when iteration is the better tool, and how divide-and-conquer and backtracking build on the same machinery. Interviewers probe this because most tree, graph, and combinatorial problems fall apart without a solid recursive mental model.
part ofData structures & algorithmsoverview, primer and where to startread it →on this pageshowhide
explore
- Recursion Mechanics12 questions
- Base Cases & Termination4 questions
- The Call Stack & Stack Overflow4 questions
- Tracing Recursion Trees4 questions
- Recursion vs Iteration8 questions
- Converting Recursion to Iteration4 questions
- Tail Calls & Tail-Call Optimization4 questions
- Divide & Conquer9 questions
- Split–Solve–Combine Paradigm5 questions
- Canonical D&C Algorithms4 questions
- Backtracking Framework8 questions
- Choose–Explore–Un-choose Template4 questions
- Pruning & State Restoration4 questions
- Canonical Backtracking Families13 questions
- Subsets, Permutations & Combinations5 questions
- N-Queens & Constraint Propagation4 questions
- Word Search & Grid Backtracking4 questions
- Computer Scienceskillanchors this topic
- Data Structures & Algorithmsskillanchors this topic
- AI & Data Scientistrole
- AI Engineerrole
- AI Red Teamingrole
- Android Developerrole
- Backend Developerrole
- Blockchain Developerrole
- Cyber Security Expertrole
- Data Analystrole
- Data Engineerrole
- DevOps / SRE Engineerrole
- DevSecOps Engineerrole
- Forward Deployed Engineerrole
- Frontend Developerrole
- Full Stack Developerrole
- Game Developerrole
- Java Backend Developerrole
- Java SDETrole
- Kotlin Backend Developerrole
- MLOps Engineerrole
- Machine Learning Engineerrole
- Network Engineerrole
- PostgreSQL DBArole
- QA Engineerrole
- Software Architectrole
- iOS Developerrole
questions
page 2 of 2In a game-move tree with 3 legal moves per position, what does searching one ply deeper cost?
basics
~20 sOne extra ply multiplies the whole search by about three: each position at the current frontier fans out into three more. Depth-limited search cost is dominated by the deepest level, so deepening is a multiplication, never an increment.
Why does a naive explicit-stack rewrite lose the work a recursion does after its recursive calls?
basics
~20 sPushing children captures only the descent. A real frame also remembers where to resume, because the parent still owes work once its children finish. Push each node twice with a phase tag so the parent is revisited after its subtree completes.
Why do many runtimes decline tail-call elimination despite the free stack win?
basics
~10 sEliminating a tail call discards the caller's activation record, and those records are what stack traces, debuggers, profilers and caller-chain security checks read. Runtimes that prize diagnosability refuse the trade deliberately, not by oversight.
Quicksort blows the stack on a year of already-ordered sensor timestamps — how do you bound its recursion depth?
basics
~20 sOrdered input makes every split lopsided, so the recursion holds one frame per record. Recurse into the smaller partition and loop on the larger — the smaller side is at most half, capping depth at log n.
In a divide-and-conquer closest-pair search over drop coordinates, what must the combine step do?
basics
~20 sThe combine step must check pairs that straddle the dividing line, since the closest pair overall may have one point on each side. It stays cheap by using the recursion's own distance to bound the search to a narrow band.
Generating permutations of a multiset, why must sort-and-skip test that the earlier twin is unused?
basics
~20 sSorting makes equal items adjacent so the check can be local. The guard then fixes one canonical order among identical items: a twin may only be placed once its left neighbour already is. Reverse the test and the second twin can never be placed at all.
Searching a grid for many target sequences at once, why prune on prefixes rather than full matches?
basics
~20 sA membership test only rules a branch out at full target length, by which point the whole subtree has already been explored. A prefix test rules it out at depth d and discards everything beneath — and the subtree beneath is where all the cost lives.
In backtracking, when is copying the state into each call better than mutating and undoing?
basics
~20 sCopy when the state is small or the recursion shallow, buying safety with the constant factor. Copying costs the state's size at every node and one live copy per level; mutate-and-undo costs little but demands a restore on every exit.
A backtracking enumerator exhausts memory collecting every valid roster — what do you change?
basics
~20 sStop materialising the output. Every arrangement here is valid, so nothing can be cut from the search; the memory goes on the returned collection. Hand each solution to a consumer at the leaf, or fold it into a count or aggregate.
Why can a digit-stripping recursion with an n == 0 base case never terminate on negative input?
basics
~20 sBecause the termination argument silently assumes integer division rounds toward zero. Under rounding toward negative infinity the value sticks at -1 and never equals 0. Negating the input first is not a safe fix: the most-negative fixed-width value has no positive counterpart.
Your recursive log parser passed every test, then died at 3 a.m. on a million-record chain — why was that inevitable?
basics
~20 sRecursion depth tracked input size, so thousand-record fixtures held a thousand frames while the production chain demanded a thousand times more than the stack region could hold. Stack exhaustion has no warning curve: it works, then it aborts.
In a drawn game-search tree, how do you tell that different move orders re-explore the same position?
basics
~20 sLabel every node with the arguments the invocation received — the position and the remaining depth — instead of with the move that led there. Repeated labels are repeated work: identical labels have identical subtrees beneath them.
Your recursive catalogue walk overflowed the stack in production — do you convert it to an explicit stack?
basics
~20 sFirst establish whether the depth was legitimate. If real data is genuinely that deep, an explicit stack moves the frames into memory that grows on demand and fixes it. If a cycle or bad parent link caused it, conversion only turns a fast crash into an out-of-memory.
Before relying on tail-call elimination for unbounded input, what must you establish?
basics
~20 sA specified guarantee from the target, plus its scope: self-recursion only or general tail calls, which build modes it covers, whether the call still qualifies inside exception handlers. A large passing test is an observation, not a guarantee.
When is a divide-and-conquer rewrite worth it over a working quadratic scan of a few thousand points?
basics
~20 sWhen measured headroom, not asymptotics, says so. A quadratic scan over a few thousand points is a few million tight comparisons and often fits the budget; the decision turns on projected growth, tail latency today, and maintenance risk.
Your feature-flag test matrix has 30 flags — do you still enumerate all 2^n configurations?
basics
~20 sNo. Thirty flags means over a billion configurations, and no pruning trick rescues an exponent you have no constraints to prune with. The work becomes scoping: enumerate only within interacting groups, encode real constraints, cover the rest pairwise, and cap flag growth.
A pruned backtracking search must run inside a request latency budget — how do you decide whether it can ship?
basics
~20 sPruning improves the average case, never the exponential worst case, so measurements on today's traffic cannot promise a latency bound. Ship only behind a bounded input size, a hard node budget with a defined fallback answer, and alerting on cap-hits.
Recursion overflows on deeply skewed input: how do you choose between an explicit stack, reshaping the data, or capping depth?
basics
~20 sDecide by what removes the failure class versus what the team can maintain. Reshaping the data bounds depth permanently but touches producers; an explicit stack keeps the algorithm and relocates linear state; caps buy time with a documented rejection.
To list every k-person roster from n engineers, how do include-exclude and index-loop recursions differ?
basics
~20 sBoth emit the same rosters. Include-exclude asks one in-or-out question per engineer, giving a binary tree of depth n. The index-loop picks the next member from those after the last chosen, giving a tree of depth k with wide fan-out.
What does forward checking add to a backtracking search beyond validating the current assignment?
basics
~20 sPlain checking looks backward, confirming the new assignment conflicts with nothing already chosen. Forward checking looks ahead: it deletes the newly illegal values from the domains of variables not yet assigned, and backtracks the moment any of those domains becomes empty.
showing 31–50 of 50