Recursion and Backtracking Questions

Recursion mechanics (base and recursive cases, tracing call stack frames, what lives on the stack versus the heap, tail calls, recursion depth limits and stack overflow diagnosis, recursion-to-iteration conversion with an explicit stack or trampoline, recursion versus iteration trade-offs) and recursion on nested data and simple divide-and-conquer (Euclid's gcd, string reversal, flattening nested lists and dictionaries lazily with generators, recursive maximum subarray). Also backtracking search over combinatorial spaces: permutations (including duplicates and the k-th permutation), subsets, combinations, combination sum, generating balanced parentheses, N-Queens (with bitmasks and symmetry), Sudoku (with minimum-remaining-values ordering), word search, palindrome partitioning, Knight's Tour and Hamiltonian paths. Covers the choose/explore/undo template, how it differs from plain DFS, state-leakage bugs, pruning, and recursion-tree complexity (O(b^d)) including call-tree counts. Memoized recursion, tree traversals, and general graph search are covered elsewhere.

EasyTechnical
46 practiced

Write a recursive Python function that returns all subsets (the power set) of a list of unique integers, preserving relative order within subsets: def subsets(nums: List[int]) -> List[List[int]]. Show the output for [1, 2, 3], explain the time and space complexity, and make sure results do not share mutable state.

EasyTechnical
45 practiced

Implement a recursive function that returns all permutations of a list of distinct integers without using library permutation helpers. Show the output for [1, 2, 3], explain how you avoid shared-state bugs, and state the time and space complexity.

EasyTechnical
42 practiced

Here is a naive recursive Fibonacci: fib(n) = n if n < 2 else fib(n-1) + fib(n-2). Draw the call tree for n = 6, count the function calls, state the asymptotic time and space, and explain what changes in the number of calls when results are cached.

That is every published Recursion and Backtracking question for Machine Learning Engineer so far. Browse the other topics in this category, or practice this one interactively.