Data Structures & Algorithms practice
Data Structures & Algorithms ยท Recursion & Sorting

Recursion & Divide and Conquer: Practice Questions

100 questions. Try each one yourself before checking the answer.

Short on time? Filter by Must Do for the 25 questions that cover this topic on their own.

Q1The Base Case And The Recursive CaseEasyMust Do

A recursive function answers two questions: when do I stop, and how does each call get closer to stopping? Write countdown(n), which prints n down to 1 and then Liftoff!, and factorial(n), which returns n!. In both, put the base case first as its own if, then the recursive case. Run factorial(5) with a depth argument that prints a line when each call starts and when it returns, indented by depth. Check factorial against math.factorial for n = 0..20. Label the code # STEP 1: (stop) and # STEP 2: (get closer).

Q2Trusting The RecursionEasy

Write sum_to(n) returning 1 + 2 + ... + n as n + sum_to(n - 1). Do not trace it. Assume the smaller call is correct and check that the step is right: that is induction. The base case proves n = 0, and the recursive case proves n from n - 1. Check it against n * (n + 1) // 2 for n = 0..900. Then break the base case on purpose (n == 1 returns 0) and print what the induction predicts: every answer is wrong by the same amount.

Q3The Call Stack, DrawnEasyMust Do

Every call gets its own frame holding its own n. Instrument factorial(4) so that each call prints a push line when it starts and a pop line with its return value when it finishes, indented by depth, and tracks how many frames are alive. Calls go down first and the multiplications happen on the way back up. Count the frames alive at the deepest point and show that it is n (the base case is n <= 1, so factorial(1) is the deepest frame). Label the code # STEP 1: through # STEP 3:.

Q4Tracing By HandEasy

Three tiny functions each append to a log list. before(n, log) appends n and then calls itself on n - 1. after(n, log) calls itself on n - 1 and then appends n. both(n, log) appends "in" + str(n), calls itself, and then appends "out" + str(n). Base case: n == 0 does nothing. Write your prediction for n = 3 as literal lists first, then run the functions and compare. Work done before the call happens in call order; work done after it happens in reverse. Check the rule for n = 0..8.

Q5Recursion Against IterationEasy

Write each of these twice, once recursively and once with a loop: factorial(n), the sum of a list (by index, no slices), and x^n as n multiplications. Check that they agree. Both versions are O(n) time, but the recursive one holds O(n) frames on the stack where the loop holds O(1), and pays for a call per step. Measure the peak number of frames for the list sum, then time all three with best_of(fn, repeats=3) (min of 3 runs).

Q6How Deep Can Python GoEasyMust Do

sys.getrecursionlimit() is the number of frames Python allows on its stack, 1000 by default. Print it. Write a probe that recurses until RecursionError, remembering the deepest depth it reached, and catch the error and print its type. Do not print the measured depth: the frames already on the stack depend on how the script is started. Print comparisons instead: the deepest depth is just below the limit, and a probe started from 300 frames down gets about 300 fewer. Then measure what a frame costs in time. Label the code # STEP 1: through # STEP 3:.

Q7RecursionError, Caught And ReadEasy

Three recursive functions never stop: one with no base case, one whose base case the input skips (n == 0 reached from n = -1), and one that steps by 2 from an odd n and so jumps over 0. Run each until RecursionError, catch it, and print type(e).__name__. Then fix each with a base case that every input reaches (n <= 0). Catching the error is a diagnosis, not a fix. Fuzz the fixed versions against a loop over n = -6..40, counting any exception as a failure.

Q8Raising The LimitMedium

A 2,000-deep recursion fails at the default limit. Show that with sys.setrecursionlimit(3000) set inside a try/finally that restores the old value, it finishes, and print that the limit was restored. Say why the limit exists: older CPython ran every Python call on the C stack, so a high limit could crash the process with no traceback. CPython 3.11+ keeps Python frames off the C stack, but code that recurses through C, such as json.dumps on a 100,000-deep list, still has its own guard and raises RecursionError: show that at the default limit. Never try to cause the crash. The robust fix for depth is a loop.

Q9Tail Calls And No TCOMediumMust Do

A tail call is the last thing a function does: sum_acc(n, acc) ends with return sum_acc(n - 1, acc + n), carrying the running total in acc. Some languages reuse the frame for a tail call (tail-call optimisation). CPython does not, and tracebacks need the frames, so the tail version fails near the limit just like the plain version n + sum_plain(n - 1). Show that both raise RecursionError at n = 5000. Then do the mechanical rewrite: rebind the parameters and loop. Check that all three agree for n = 0..800, and run the loop at n = 10^6. Label the code # STEP 1: through # STEP 3:.

Q10Recursion On A List, By IndexEasy

Write rsum(a, i), which returns a[i] + rsum(a, i + 1) with i == len(a) as the base case, then rcount(a, x, i) (how many items equal x) and rmax(a, i) the same way. Pass an index, never a slice. The base case must handle the empty list: rsum and rcount return 0, and rmax raises ValueError like max([]) does. Fuzz all three against sum, list.count and max on seeded lists of 0 to 60 items, counting any unexpected exception as a failure. Keep inputs under 900 items.

Q11The Hidden Cost Of SlicingMediumMust Do

A recursive sum that writes a[0] + rsum(a[1:]) looks as cheap as the index version, but a[1:] copies the rest of the list on every call. Write both versions: rsum_slice(a) and rsum_idx(a, i). Check them against sum(). Then measure, for n = 200, 400 and 800, the best-of-3 time and the tracemalloc peak of each. Print the growth from n = 200 to n = 800 for both measures, and decide from those printed numbers (not from a fresh run) which version grows faster. Label the code # STEP 1: through # STEP 3:.

Q12Reversing A StringEasy

reverse(s) = reverse(s[1:]) + s[0] looks elegant, but it slices and concatenates at every level. Write it, and write an index version that appends characters to one list and joins once. Check both against s[::-1] on seeded random strings (catch exceptions and count them as failures). Count how many characters each version copies for lengths 100, 200, 400 and 800, and time them. Print the counts and the times, and conclude only from the counts.

Q13Palindromes RecursivelyEasy

DSA Topic 4 checked a palindrome by walking two pointers inward with a loop. Turn each step of that loop into a call: is_pal(s, lo, hi) on the half-open range [lo, hi) compares the two ends and recurses inward. Normalise first (lowercase, letters only). Count the calls for palindromes of length 10, 11 and 1,500. Fuzz it against t == t[::-1] and against the loop. Then show that a 3,000-letter palindrome exhausts the stack (catch it, print the type) while the loop copes.

Q14Recursion On DigitsEasy

Strip the last digit with n % 10 and recurse on n // 10. Write digit_sum(n), digit_count(n) and to_base(n, b) (for bases 2 to 36, with n >= 0). Show that the depth is the number of digits, which is O(log_b n): any int below 10^19 needs at most 19 frames. Check against str(), int(s, b) and format(n, 'b') on seeded inputs up to 10^30, counting exceptions as failures.

Q15Flattening A Nested ListMediumMust Do

flatten([1, [2, [3, [4]], 5]]) should give [1, 2, 3, 4, 5]. Write two versions. flatten_down recurses into an item that is a list and appends everything else to one output list that is passed down. flatten_up returns a fresh list from each call and concatenates the results. A string is a value, not something to recurse into. Check both against a seeded oracle: build nested lists by cutting a known flat list at random, so the flattened result must equal it (empty sublists included). Show that the stack depth is the nesting depth, not the length. Then compare the two on a deeply nested list with a wide innermost list: count the items each version copies, and time them. Label the code # STEP 1: through # STEP 4:.

Q16Nesting DepthEasy

nesting_depth(x) is 0 for a non-list and 1 plus the deepest part for a list, so [] has depth 1. Write it, then write a second walk that counts the integers at each depth into a dict (an integer's depth is the depth of the list that holds it). Fuzz both against a scan of repr(x) that tracks the running bracket depth. The nesting depth bounds the stack any recursive walk of x needs: record the most frames alive during the counting walk and check it against the depth.

Q17Recursion Over A DictMedium

A nested config dict has dicts inside dicts. Write count_values(d) (the non-dict values), key_paths(d) (every path to a non-dict value as a tuple such as ('db', 'host')), and get_path and set_path that follow a tuple. Dicts keep insertion order, so the path list prints the same every run. Show why tuple paths beat joining keys with dots. Check that set_path rebuilds a seeded random dict from its own paths, and count any exception as a failure.

Q18Two Recursive CallsMedium

Naive fib(n) = fib(n - 1) + fib(n - 2) calls itself twice. Count the calls: calls(n) = calls(n - 1) + calls(n - 2) + 1, which works out to 2 * fib(n + 1) - 1. Print the calls for n = 5..27 beside that formula, and the ratio of consecutive counts, which settles near 1.618. Then print the indented call tree for fib(5) and count how many times each argument is computed from the printed lines.

Q19Memoisation With A DictMediumMust Do

Naive Fibonacci redoes the same subproblems. Write it first and count its calls and time for n = 27. Then write a version that stores each fib(k) in a dict named memo the first time it is computed, and looks there first. Count its calls (about 2n), time it, and compute the speed-up from the two printed times. Check it against an iterative Fibonacci for every n up to 300, then answer n = 800 and print the digit count. State the time, space and depth. functools.lru_cache is the library form, and DSA Topic 21 fills the same values bottom-up in a table; you build neither here. Label the code # STEP 1: through # STEP 4:.

Q20Counting Grid PathsMedium

How many paths lead from (0, 0) to (r, c) if you may only move right or down? paths(r, c) = paths(r - 1, c) + paths(r, c - 1), with 1 when r == 0 or c == 0. Count the naive calls for grids with r + c up to 20, and compare them with a dict memo keyed on (r, c). Check both against math.comb(r + c, r) on every small grid, then let the memo answer a 100 by 100 grid. Print the memo's entry count and explain it.

Q21functools.lru_cacheMedium

A dict named memo stores each answer the first time it is computed. Python ships that idea as a decorator. Write the dict-memo Fibonacci, then two decorated versions: one with @lru_cache(maxsize=None) and one with @cache (both from functools). Call each with fib(30) from a cold start and print cache_info(): the misses are the calls that really ran the body, the hits are the calls answered from the cache. Show that the numbers match n + 1 misses and n - 2 hits, call the function again and watch one more hit appear, then use cache_clear() and show the counters reset. Check all three against an iterative Fibonacci for n = 0..300, and print the time of each for a cold fib(500) (clear the cache inside the timed call). Finally show that arguments must be hashable (DSA Topic 7): a cached function that takes a list raises TypeError, and a tuple works. From here on, lru_cache and cache are free to use. State time, space and depth.

Q22Binary Search, RecursivelyEasy

DSA Topic 3 searched a sorted list with a loop. Write the same lower-bound search as recursion: lower_bound(a, x, lo, hi) over the half-open range [lo, hi), which discards one half per call. Pass lo and hi, never a slice. Track the depth with a depth argument. Show that a search in a million items goes about log2(n) frames deep (print the frame count beside n.bit_length() + 1), fuzz it against bisect.bisect_left on seeded lists with many duplicates (count exceptions as failures), and wrap it into a search that returns an index or -1. Then time the recursive version, the loop and bisect on the same 2,000 queries. State time, space and depth.

Q23Fast ExponentiationMediumMust Do

Computing x^n with a loop takes n - 1 multiplications. Squaring does better: x^n = (x^(n // 2))^2, and one more factor of x when n is odd. Write power(x, n, mod, muls) recursively with the base case first, counting every multiplication in the one-item list muls. Label the code # STEP 1: through # STEP 4:. In step 1, write the recursion and the naive loop and count their multiplications for n = 10, 1000 and 10**6 (use a modulus so the numbers stay small), and compare the fast count with bit_length + popcount. In step 2, fuzz both forms against pow(x, n) and pow(x, n, m) on seeded inputs, counting exceptions as failures. In step 3, time power(3, n) without a modulus for n = 50_000, 100_000, 200_000 and 400_000: big-integer multiplication is not O(1), so the time should grow faster than n. In step 4, say what C or Java would do. State time, space and depth.

Q24Recurrence RelationsMedium

A recurrence describes the cost of a recursive function in terms of smaller calls. For each of five functions, write the recurrence in a comment, unroll it to a closed form, then check the closed form by counting steps in an instrumented run at several n: factorial (T(n) = T(n - 1) + 1), the slicing sum (T(n) = T(n - 1) + n, counting one unit per call plus one per item copied), binary search for an absent small value (T(n) = T(n/2) + 1), fast power (T(n) = T(n/2) + 1) and naive Fibonacci (T(n) = T(n - 1) + T(n - 2) + 1). Print a table of measured against closed form, and a final line that says whether all of them matched.

Q25Recursion Or NotEasy

Ten small problems arrive, each as a recursive function. Route each to one of four answers: a loop (a linear walk, or a recursion that overflows the stack), memoised recursion (the same subproblem is asked more than once), divide and conquer (a flat input split into independent halves) or plain recursion (nested data). Do not guess: write a probe that wraps a function and measures, for one run, the number of calls, the number of distinct arguments, the most children any call makes, and whether it raised RecursionError. Write a route function that uses only those measurements and whether the input is nested, print a table, and check that every row was routed the way its author intended.

Q26Sum And Max By HalvesEasyMust Do

Divide and conquer splits a problem into independent halves, solves each and combines. Label the code # STEP 1: through # STEP 4:. In step 1, write total(a, lo, hi, depth, stats) over the half-open range [lo, hi): an empty range returns 0, a one-item range returns its item, otherwise it adds the totals of the two halves. Run it on 1,000,000 items, check it against sum(), and print the deepest frame count beside limit. In step 2, write the one-item-at-a-time version and show that it raises RecursionError on the same input, printing only the exception type. In step 3, write biggest the same way (an empty range raises ValueError, like max([])), fuzz both halves-functions against sum() and max() on seeded lists of sizes 0..40 (at size 0 expect ValueError from biggest and from max; count any other exception as a failure), and compare call counts and times on 900 items. In step 4, state the recurrence: the work is the same O(n) as the loop, but the depth drops from n to log2(n). State time, space and depth.

Q27Counting And FindingEasy

Write three recursive functions over a list, all by index with the base case first: count_x(a, x, i) counts the items equal to x; first_index(a, x, i, calls) returns the first index of x or -1 and stops as soon as it finds it; all_indices(a, x, i, out) appends every index of x to out. Fuzz them against a.count, a.index and a list comprehension on seeded lists (count exceptions as failures). Show that first_index makes k + 1 calls when x is at index k and n + 1 calls when x is absent. Then show a broken first_index that forgets the return on its recursive call, and print what it gives beside the truth. State time, space and depth.

Q28Checking SortednessEasy

Write two recursive checks that a list is in non-decreasing order, both by index. sorted_by_index(a, i) compares a[i] with a[i + 1] and recurses on the rest. sorted_by_halves(a, lo, hi) checks the two middle items, then that each half is sorted. Fuzz both against all(a[i] <= a[i + 1] ...) on seeded lists that are sorted half of the time and have one swap the other half (count exceptions as failures). Count calls on a sorted list of 800 items and on one with a violation near the front. Then show two plausible bugs and print their wrong answers beside the truth: using < instead of <=, and skipping the check across the middle. State time, space and depth for each.

Q29Generating All SubsetsMediumMust Do

Every item is either in a subset or out of it, so a list of n items has 2^n subsets. Label the code # STEP 1: through # STEP 4:. In step 1, write subsets(items, i, current, out, calls): the base case copies current into out; the recursive case includes items[i] (and removes it again afterwards), then excludes it. Print all 8 subsets of [1, 2, 3]. In step 2, count the subsets, the calls and the total items stored for n = 4, 8, 12, 16 and check them against 2^n, 2^(n+1) - 1 and n * 2^(n-1). In step 3, check the output for every n <= 12 and for n = 16 against itertools.combinations over every size, as sorted lists, and show the bug of forgetting to copy current. In step 4, time n = 10..16. State time, space and depth, and say that this is a preview of backtracking (DSA Topic 19 adds pruning).

Q30Generating PermutationsMedium

A permutation is an ordering. To generate them all, pick each unused item as the next one, recurse to order the rest, then put the item back. Write permute(items, used, current, out, calls) with a used list of flags. Print all 6 permutations of [1, 2, 3], then count the n! permutations and the calls for n = 1..8, check the calls against sum(n! / (n-k)!), and compare the output with list(itertools.permutations(items)) for every n <= 8 (it matches in order, because the items are tried in sorted order). Time n = 1..8 and use the per-permutation time to estimate, from the printed numbers, how long n = 15 would take. State time, space and depth.

Q31Combinations Of Size kMedium

Choose k items from a list and keep their order, so [1, 2, 3, 4] with k = 2 gives (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4). Write combos(items, i, k, cur, out, calls) with two choices for items[i]: take it (one fewer item still needed) or skip it. The base case comes first and stops as soon as k == 0, and a second stop fires when fewer than k items remain. That second stop is the simplest pruning there is, and the answer should name it (DSA Topic 19 prunes much harder). Also write combos_no_cut, which only stops at the end of the list, and count the calls of both for n = 16 and several k. Check the output of combos against itertools.combinations (same items, same order) and against math.comb for every n <= 10 and every k, plus n = 16, counting exceptions as failures. State time, space and depth.

Q32Permutations With RepeatsMedium

The string "aab" has 3! = 6 orderings of its positions but only 3 distinct strings. Write perms_all(chars, used, cur, out, calls), which picks each unused position in turn, collects the strings and dedupes with a set (print them sorted). Then write perms_counter(counts, left, cur, out, calls), which picks from a collections.Counter of the remaining letters, one distinct letter per step, so every distinct string appears exactly once and no set is needed. Check that the count of distinct orders equals n! / (c1! * c2! * ...) over the letter counts, fuzz both against set(itertools.permutations(...)) on seeded strings (count exceptions as failures), and print the calls of each for "aab", "aabb", "aaabbb" and "aaabbbcc", with the time for the last. State time, space and depth.

Q33k-Sum, RecursivelyMedium

DSA Topic 4 solved 3-sum and 4-sum with fixed loops and a two-pointer pair walk. Loops cannot handle "any k", but recursion can. Write k_sum(nums, target, k) that sorts once with sorted() and calls a helper ksum_from(nums, lo, target, k, cur, out, steps) over indices. The base case is k == 2: the two-pointer pair walk on nums[lo:], written with indices. Otherwise fix one value nums[i] (skipping a value equal to the previous one at the same level, so no duplicate answers appear) and recurse with k - 1, target - nums[i] and i + 1. Return the distinct value tuples in sorted order. Fuzz it for k = 2..5 against set(itertools.combinations(sorted(nums), k)) filtered by sum on seeded lists full of duplicates, counting exceptions as failures. Then count the pair-walk steps for doubling n and k = 3 and k = 4, and print the ratio beside 2^(k-1). State time, space and depth.

Q34Tower Of HanoiMediumMust Do

Three pegs A, B, C hold n disks, the largest at the bottom of A. Move them all to C, one disk at a time, never placing a disk on a smaller one. Recursion makes it short: move the top n - 1 disks to B, move the largest to C, then move the n - 1 disks from B onto C. Label the code # STEP 1: through # STEP 4:. In step 1, write hanoi(n, src, dst, spare, moves, depth, stats) with the base case first (n == 0), recording (disk, src, dst), counting each move with a counter and tracking the deepest depth. Print the 7 moves for n = 3. In step 2, count moves and calls for n = 1..20 with a counter and check 2^n - 1 moves, 2^(n+1) - 1 calls and a deepest frame count of n + 1. In step 3, using the recorded moves for n <= 12, check that the largest disk moves exactly once, at position 2^(n-1) - 1, and that disk d moves 2^(n-d) times. In step 4, time n = 10, 12, 14, 16. State the recurrence T(n) = 2T(n - 1) + 1, time, space and depth.

Q35Hanoi, Checked By SimulationEasy

A move list is only trustworthy if something replays it. Write simulate(n, moves), which keeps three lists as pegs (disk n at the bottom of A to start), applies every move, and raises ValueError if a move takes from an empty peg, takes a disk that is not on top, or places a disk on a smaller one. Run it on the recursive solver's moves for n = 0..14 and print the final pegs for n = 4. Then write the mistake a student makes first, hanoi_bad, which moves the n - 1 smaller disks to the wrong peg, and let simulate find the first illegal move. Finally, snapshot the pegs at the moment the largest disk moves and check that it sits alone on A, the other n - 1 disks form a tower on B, and C is empty. Use that to explain why 2^n - 1 is also the minimum number of moves. State time, space and depth.

Q36Counting Ways With A MemoEasy

Two counting problems with the same shape. A staircase of n steps can be climbed in steps of 1, 2 or 3: stairs(n) = stairs(n - 1) + stairs(n - 2) + stairs(n - 3), with one way to climb 0 steps and none for a negative number. A 2 x n strip can be tiled with 2 x 1 dominoes: tiles(n) = tiles(n - 1) + tiles(n - 2). Write each as plain recursion with a call counter, and again with @cache (from functools). For n = 6, 10, 14, 18, print the plain call counts, the cached cache_info() misses and hits, and check that misses equals the number of different arguments ever asked for (n + 3 for stairs, because -1 and -2 are asked for, and n + 2 for tiles). Check both against an iterative loop for n = 0..300 and note that tiles(n) is Fibonacci. State time, space and depth, and say that DSA Topic 21 builds these bottom-up.

Q37Pascal's Rule, MemoisedMedium

The number of ways to choose k from n obeys C(n, k) = C(n - 1, k - 1) + C(n - 1, k), with C(n, 0) = C(n, n) = 1. Write it as plain recursion with a call counter, show that its call count is exactly 2 * C(n, k) - 1 (every call either returns a 1 or splits in two, so the calls form a full binary shape with C(n, k) ones at the ends), and print the counts for n = 8, 12, 16, 20 with k = n // 2. Then add @cache (from functools) and print the number of distinct calls (cache_info().misses) beside the upper bound (k + 1) * (n - k + 1), which counts every (n - a, k - b) the recursion can reach. Check the cached version against math.comb for every n <= 60 and every k, and time n = 20 plain against cold cached. State time, space and depth.

Q38Collatz Lengths With A Shared MemoEasy

From n, halve it if it is even, otherwise take 3n + 1; the number of steps to reach 1 is its Collatz length (steps(1) = 0). Write steps(n, memo, depth, stats) recursively with the base case first, and share one dict across every start from 1 to 100,000, so a chain that meets an earlier number stops there. Print the start with the longest chain, its length, the number of calls with the memo, and the number of calls without it, found by adding steps(n) + 1 over all starts. Prove that count on small ranges by running the unmemoised recursion for 1..2000. Check lengths against a loop for 1..3000. Print the deepest recursion depth and explain why it stays far below the recursion limit here, and why no theorem guarantees it in general. State time, space and depth.

Q39Mutual RecursionEasy

Two functions can call each other. Write is_even(n) and is_odd(n): is_even(0) is True, is_odd(0) is False, and each otherwise asks the other about n - 1. Print the trace for is_even(4) with a depth argument and show that the two names alternate on one call stack. Show that is_even(500) works but is_even(5000) raises RecursionError (catch it, print the type name) and that n % 2 is the fix. Then Hofstadter's female and male sequences: F(0) = 1, M(0) = 0, F(n) = n - M(F(n - 1)) and M(n) = n - F(M(n - 1)). Print F and M for n = 0..19, check for n <= 300 that F and M never decrease, never jump by more than 1, and that F(n) stays within 1 of (n + 1) / phi (the golden ratio), and compare plain call counts with @cache (from functools) for n = 10, 15, 20. Warm the cache in increasing order for n = 300. State time, space and depth.

Q40Walking Nested JSONMediumMust Do

JSON documents nest dicts and lists as deep as they like (this shape is a tree, DSA Topic 13). Label the code # STEP 1: through # STEP 4:. In step 1, json.loads a fixed document that nests dicts and lists (include null, true, numbers, strings, an empty dict and list, and a value that is the string "id"). Write one walker walk(x, path, visit) that handles dicts and lists alike, calling visit(path, x) on every item before its parts; a string is a value, never a sequence to recurse into. In step 2, use it to count values by type name, list every path (a tuple of keys and indexes) that ends in a key named "id", and compute the maximum nesting depth with a recursive nesting(x) (a scalar is 0, a container is 1 + its deepest part, so {} is 1). In step 3, show the bug of treating strings as lists: a count_bad that loops over any str or list raises RecursionError, because a one-character string contains itself. In step 4, fuzz the walker on 500 seeded random documents against an explicit-stack counter (type counts and maximum depth), and check that every "id" path resolves back to its value, counting exceptions as failures. State time, space and depth.

Q41Deep Copy, Shared Parts IncludedHard

A shallow copy such as list(doc) makes a new outer list but reuses the inner lists, so changing a part of the copy changes the original. Show that with shared = [1, 2] and doc = [shared, shared, {"k": shared}]. Then write deep_copy_plain(x, calls), which recurses into every list and dict and returns scalars as they are. It follows every reference, so a part reachable twice is copied twice and the copy no longer shares anything. Write deep_copy(x, memo, calls) that fixes this: a dict memo maps id(original) to its copy, a container already in memo returns the same copy, and the new container is registered before its parts are copied. Write sharing(x), which walks a structure and returns a list that labels each container ("new", k) the first time it is met and ("again", k) after, so two structures with equal sharing have the same shape and the same sharing pattern. Fuzz deep_copy on 400 seeded documents that reuse finished parts (lists and dicts, depth at most 5) against copy.deepcopy: equal by ==, equal sharing, and no container in common with the original (compare id sets), counting exceptions as failures. Count how many documents had sharing and on how many deep_copy_plain changed the pattern. Finally build diamond(16) (x = [x, x] sixteen times over [0]) and compare the calls and the number of distinct containers in the original, in the plain copy and in the memo copy. State time, space and depth.

Q42Transforming Nested DataMedium

Write three functions that each rebuild a nested structure of lists and dicts and keep its shape: double_numbers(x) doubles every int and float (a bool is not a number here, leave it alone), rename_keys(x, names) renames dict keys through a mapping and keeps unmapped keys, and prune(x) drops every empty list and empty dict, including a container that only becomes empty after its own empty parts were dropped. Each returns new containers and never mutates its input. Show the bug of a student version bad_double that tests isinstance(x, (int, float)) and mutates in place: print what it does to [True, 3] beside the truth, and print the input afterwards. Fuzz the three on 400 seeded documents (depth at most 5, containers of 0 to 3 parts), taking a copy.deepcopy snapshot first and checking the input still equals it afterwards. Use leaf-order oracles from an explicit-stack leaves(x): the doubled leaves equal the original leaves with numbers doubled, renaming with {"a": "A", "b": "B"} and then back with the inverse restores the document, and prune keeps the leaves in order, leaves no empty container, and is idempotent. Count exceptions as failures. State time, space and depth.

Q43Evaluating A Nested ExpressionMedium

An expression is either a number or a list [operator, part, part, ...], where every part is an expression, so ['+', 2, ['*', 3, 4]] means 2 + 3 * 4. (This shape is a tree, named in DSA Topic 13; here it is just nested lists.) Write evaluate(e) for the operators +, *, - (the first part minus the rest, or negation with one part), max and min: evaluate the parts, then apply the operator. A list with no parts or with an unknown operator raises ValueError. Write bracketed(e), which prints the expression fully bracketed, for example (2 + (3 * 4)) and max(1, (2 - 3)). Print five worked examples, then fuzz on 400 seeded expressions (depth at most 4, one to three parts each) that are generated together with their expected value and their list count, computed by an independent fold while building. Check the value, and check that bracketed has exactly one ( per list and balanced brackets, counting exceptions as failures. State time, space and depth, and say what the depth equals.

Q44Pre-Order With An Explicit StackMediumMust Do

A pre-order visit handles an item before its parts. For a nested list the visit records ("list", len(x)) for a list and the value itself for anything else. Label the code # STEP 1: through # STEP 4:. In step 1, write pre_rec(x, out, stats, depth=0), recursive, which also records the deepest call in stats. Write pre_stack(root, reverse_push=True), which uses a plain list as a stack (DSA Topic 10 teaches the stack): pop an item, record it, and push its parts so that the first part comes off first, which means pushing them in reverse. It also returns the largest size the stack reached. Trace [1, [2, [3, 4]], 5] showing the stack before each pop. In step 2, show the bug of reverse_push=False (the last part is visited first) printing the wrong order beside the truth. In step 3, fuzz both on 500 seeded nested lists (depth at most 6, 0 to 4 parts), counting exceptions as failures, and compare the peak stack size with the recursion depth on a wide list of 1,000 items. In step 4, build a list nested 100,000 deep with a loop: the recursive version raises RecursionError (print the exception type), the stack version finishes. State time and space for both.

Q45Closest Pair On A LineMedium

Given at least two numbers, find the pair with the smallest difference. Report it as a tuple (gap, smaller, larger), so ties resolve by the tuple order. Write the brute force closest_truth(nums) over itertools.combinations (O(n^2)). Then write the divide and conquer on a list sorted once with sorted(): closest_dc(xs, lo, hi, calls) on the half-open range [lo, hi). The closest pair is inside the left half, inside the right half, or across the middle, and across the middle, in sorted order, only the two points beside the split can be it. Write closest_scan(xs), one pass over the adjacent gaps. Fuzz both against the brute force on 800 seeded lists with duplicates and negatives, counting exceptions as failures. Time the brute force against the divide and conquer for 1,500 numbers, then time the sort, the divide-and-conquer walk and the scan separately for 100,000 numbers, and print the call count. State time, space and depth, and what the exercise teaches about divide and conquer.

Q46Maximum Subarray By Divide And ConquerHardMust Do

The maximum subarray is the non-empty run of consecutive items with the largest sum. Label the code # STEP 1: through # STEP 4:. In step 1, write the O(n^2) brute force max_sub_brute(a) (running sums from every start), which will serve as the oracle. In step 2, write max_sub_dc(a, lo, hi, touched) on the half-open range [lo, hi): the best subarray lies in the left half, in the right half, or crosses the middle. The crossing best is the best suffix of the left half (ending at mid - 1) plus the best prefix of the right half (starting at mid), each non-empty, found in one O(n) walk each. State the recurrence and count the items touched by the crossing walks for n = 2^6 to 2^12. In step 3, fuzz both against the brute force on 1,500 seeded lists plus 300 lists of all-negative numbers, counting exceptions as failures. In step 4, write the scan of DSA Topic 2 (Kadane) and time all three for n = 2,000 (brute force) and divide and conquer against Kadane for n = 10,000, 20,000 and 40,000, printing the times and the doubling ratio of divide and conquer. Say what you found. State time and space.

Q47Majority By HalvesMedium

A majority value appears strictly more than n / 2 times. Write majority_dc(a, lo, hi, visits) on [lo, hi): find each half's majority candidate by recursion, and if both agree return it; otherwise count each candidate over the whole range (one O(n) pass, added to visits) and return the one whose count beats half, or None. The reason it works: if x is a majority of the whole range, it must be a majority of at least one half, because the two halves hold at most floor(l/2) + floor(r/2) <= n/2 copies of it if it is not. State T(n) = 2T(n/2) + n = O(n log n). Show the bug of majority_left_only, which only trusts the left half's candidate: print it beside the truth on [1, 2, 2] and count its failures in the fuzz. Fuzz the correct version on 1,500 seeded lists against a Counter (counting exceptions as failures). Then compare the item visits and time against Boyerโ€“Moore from DSA Topic 2 (candidate pass plus a verifying pass) on 50,000 items with a planted majority. State time and space.

Q48All Interleavings Of Two StringsMedium

An interleaving of "ab" and "xy" mixes their letters while each string keeps its own order, so "axby" and "abxy" count and "baxy" does not. Write interleave(s, t, i, j, cur, out, calls): the base case (both strings used up) comes first, otherwise take the next letter of s or the next letter of t, in that order, undoing each choice afterwards. Print the six results for "ab" and "xy". For every pair of lengths m, n from 0 to 6 (letters all distinct), check that the output has C(m + n, m) strings, that it equals the strings built from itertools.combinations of positions for s (same order), and that removing the letters of t leaves s again. Print leaves and calls for several sizes up to 8 and 8. Then show that repeated letters make duplicate strings: "aa" with "aa" gives 6 results but 1 distinct string. State time, space and depth.

Q49Patterns Printed By RecursionEasy

Where the output happens, before or after the recursive call, decides the shape. Write ruler(n, out), which appends a row of k dashes for each tick: ruler(n - 1), then the tick of length n, then ruler(n - 1), so n = 3 gives lengths 1 2 1 3 1 2 1. Print it with each row's length. Then write ruler_pre (tick before both recursive calls) and ruler_post (tick after both), and three triangle functions over rows of stars: grow (row, then recurse) for n = 4, shrink (recurse, then row), and hill (row, recurse, row again, with the base case at the peak). Write the predicted row lengths as literal lists in the code before running, then run and compare. Check the ruler's tick lengths for n <= 12 against the closed form (i & -i).bit_length() for the i-th tick, and its count and calls against 2^n - 1 and 2^(n+1) - 1. State time and space (depth).

Q50From Statement To RecursionEasy

Given a problem statement, the shape of the recursion follows from a few questions about it. Write ten statements: the factorial of 20; adding up 100,000 numbers; finding a value in a sorted list of 1,000,000; adding every number in a list nested 3 levels; adding every number in a list nested 3,000 levels (built with a loop); listing all subsets of 10 items; counting the ways to climb 80 stairs in steps of 1 or 2; x^n mod m for n = 10^9; counting the orderings of 7 people; and the 80th Fibonacci number. Each statement carries features: is the data nested, how deep is the natural recursion, does it enumerate every choice, do calls repeat the same question (measured by counting the arguments of a small naive prototype, not asserted), and can halves split or discard the work. Write one route(features) with ordered rules that returns one of: one-step recursion, halves (divide and conquer), generate every choice (DSA Topic 19 prunes), repeated subproblems (memo, DSA Topic 21), nested data (recursion or an explicit stack) or loop (deep and linear). Write the expected route for each statement as a literal before routing, assert they agree, then run the routed solution for each and check it against an oracle. Add the evidence for the two cases where the wrong tool fails. State the cost of route and of each solution.

Q51Counting InversionsHardMust Do

An inversion is a pair of positions i < j with a[i] > a[j], so [2, 4, 1, 3, 5] has 3 of them: (2, 1), (4, 1) and (4, 3). Label the code # STEP 1: through # STEP 4:. In step 1, write the O(n^2) brute force inversions_brute(a) and use it as the oracle. In step 2, divide: write count_inv(a, lo, hi) on the half-open range [lo, hi), which counts the inversions inside the left half, inside the right half, and across the middle. For the cross count, take sorted() copies of both halves and walk them with two pointers (DSA Topic 2 merged two sorted arrays with the same pointers): for each right value r in ascending order, the left values greater than r are everything past the left pointer. Name that walk cross_count(left, right). Equal values are not inversions, so the pointer must pass left[i] <= r. Print a trace of [5, 2, 4, 1, 3, 0] with depth indentation, one line per call that splits. In step 3, fuzz 300 seeded lists (sizes 0 to 40, both a tiny value range full of duplicates and a wide one), count exceptions as failures, and check a sorted list (0), a reversed list of 1,000 (n * (n - 1) / 2) and an all-equal list (0). In step 4, time the brute force and the divide and conquer for n = 250, 500, 1000, 2000 with best_of(fn, repeats=3), print both times and their ratio, and finish with a comment on the cost: the recurrence, why it is not O(n log n), and what changes it (that algorithm has a name and a Topic). State time, space and depth.

Q52Recursion TreesMedium

A recurrence says how much work one call does and how many smaller calls it makes. Drawing the calls level by level (a recursion tree) turns the recurrence into a sum. Write level_table(n, a), a recursive walk for T(n) = a T(n/2) + n that records, for each depth, the number of calls and the total work (each call costs its own size; a call of size 1 stops). For n = 64, print the table for a = 2, a = 1 and a = 4: the level, the calls, the size per call and the work on the level, then the total and which level has the most work (the top, the bottom, or every level equally, decided from the numbers). Then, for n = 2^6, 2^10, 2^14, 2^18, compute each total from the closed form for a level (a^k * n / 2^k, no recursion) and divide it by n, n log2(n) and n^2. The right bound is the column whose ratio stays flattest, measured as the largest ratio over the smallest. Print the spreads and the choice. State time, space and depth of level_table.

Q53The Master Theorem, InformallyHardMust Do

For T(n) = a T(n/b) + f(n) with f(n) = n^d, compare d with the critical exponent e = log_b(a): if d < e the leaves dominate and T(n) = Theta(n^e); if d == e every level ties and T(n) = Theta(n^d log n); if d > e the top dominates and T(n) = Theta(n^d). Label the code # STEP 1: through # STEP 4:. In step 1, write classify(a, b, d) returning the case and the bound as text (compare floats with math.isclose). In step 2, classify seven recurrences from this topic: binary search T(n/2) + 1, fast power T(n/2) + 1, sum by halves 2T(n/2) + 1, maximum subarray by halves 2T(n/2) + n, Karatsuba 3T(n/2) + n, the 4-product multiply 4T(n/2) + n, and a cubic combine 2T(n/2) + n^3. Write the bound you expect for each beside the classifier's and print whether they agree. In step 3, check each by evaluating a memoised T(n) (with T(1) = 1) at n = 2^10, 2^15, 2^20, printing T(n) over the claimed bound and the ratio T(2n) / T(n); the three ratios to the bound should stay within a factor of 1.5 of each other. In step 4, show two recurrences the theorem does not cover because they shrink by subtraction: T(n) = T(n - 1) + n and T(n) = 2T(n - 1) + 1; compute them for n = 1..30 and compare with n(n + 1) / 2 and 2^n - 1. State time, space and depth.

Q54Post-Order With A Processed FlagHardMust Do

An expression is a number or a list [operator, part, part, ...], such as ['+', 2, ['*', 3, 4]] (this shape is a tree, DSA Topic 13). To apply an operator you need its parts' values first, so the item is handled after its parts: post-order. Label the code # STEP 1: through # STEP 4:. In step 1, write the recursive evaluator ev(x) for + (any number of parts), * (any number) and - (exactly two). In step 2, write ev_stack(x) with a list used as a stack (DSA Topic 10 teaches the stack). Each entry is an (item, processed) pair. Pop one; a number goes onto a values list. An unprocessed list is pushed back as processed, then its parts are pushed in reverse so the first part is popped first. A processed list takes its last len(item) - 1 values off values, applies the operator and pushes the result. Print the values list after each processed item for ['+', 2, ['*', 3, 4]], then show the common bug: pushing the parts forward, which reverses the arguments of - (print ['-', 10, 3] evaluated both ways). In step 3, fuzz both evaluators on 500 seeded expressions (count exceptions as failures). In step 4, build with a loop an expression ['+', 1, ['+', 1, ...]] nested 50,000 deep, show that ev raises RecursionError (print the type name) and that ev_stack finishes, with the peak stack size. State time, space and depth.

Q55Any Recursion As A LoopHard

The interpreter keeps a frame for each active call: its arguments, its local variables and where it will resume. You can keep those frames yourself, as small lists on a list used as a stack (DSA Topic 10 teaches the stack). Convert three functions this way. fib_frames(n) holds [n, resume, saved] frames and a ret variable that carries each return value to the caller: resume point 0 starts the call, 1 comes back from fib(n - 1) and saves its result, 2 comes back from fib(n - 2) and adds. hanoi_frames(n) holds [k, src, dst, via, resume] frames and appends moves to a list. sum_frames(n) converts sum_to(n) = n + sum_to(n - 1). Count the calls in each version. Check fib_frames against the recursive fib for n <= 20 (result and call count, which is 2 * fib(n + 1) - 1), hanoi_frames against the recursive hanoi move for move for n <= 10 and by count for n = 16, and run sum_frames(100_000) where the recursive sum_to raises RecursionError (print the type name). Print the stack after every step of fib_frames(3). State what you gain, what you lose, and the time, space and depth of each.

Q56A Recursive-Descent ParserHardMust Do

A grammar can be turned into functions, one per rule, that call each other: an expr is terms joined by + or -, a term is factors joined by *, and a factor is an integer or a bracketed expr. Because term sits below expr, * binds tighter than +, and a loop that builds [op, left, right] left to right groups 10-3-2 as (10-3)-2. Label the code # STEP 1: through # STEP 4:. In step 1, write tokenize(text) (integers become int, everything else stays a one-character string, spaces are skipped) and parse(text), which holds the three mutually recursive functions and one shared position pos (nonlocal). It returns the nested-list form, the deepest bracket nesting seen and the most expr/term/factor calls alive at once, and raises ValueError on an unbalanced bracket, a missing operand, a trailing token or empty text. Show '2*(3+4)-5', '2+3*4', '10-3-2' and the error cases. In step 2, write ev(x) for the nested list. In step 3, fuzz 500 seeded expression strings (no unary minus, brackets nested under 50) against Python's eval, used here only as an oracle; count exceptions as failures. In step 4, count the live calls: for 100 nested brackets print the most alive at once and that number per bracket, then show that 400 nested brackets raise RecursionError. State time, space and depth.

Q57Closest Pair In The Plane, A PreviewHard

Given n points (x, y), find the smallest distance between two of them. The brute force checks every pair, O(n^2). The divide and conquer sorts the points by x once with sorted(), splits at the middle, finds the best distance d inside each half, and then checks only the strip of points within d of the dividing line. Work with squared integer distances so there are no floats. Sort the strip by y with sorted() at each level, and compare each strip point only with the points after it whose y is within d. Each point has at most 7 such neighbours, because they must fit in a d by 2d rectangle where all points on one side are at least d apart (print the drawing of the 8 cells). Record the largest number of neighbours any point was compared with and check it is at most 7. Fuzz 300 seeded point sets (small coordinate ranges so there are ties and duplicates, plus tight clusters) against the brute force, counting exceptions as failures. Time both for n = 500, 1000, 2000. End with a comment on the cost of sorted() inside every call, the merge that removes it (a Topic that is not built here), and the expected-O(n) alternative from the hash-map topic. State time, space and depth.

Q58Fast Power On MatricesMedium

Fast exponentiation (x^n = (x^(n // 2))^2, times x when n is odd) works for anything with an associative multiply, not just numbers. Write a generic mat_mul(A, B) for square lists-of-lists and mat_pow(M, n) with the same recursion, counting matrix multiplies in a one-item list. Since [[1, 1], [1, 0]]^n = [[F(n+1), F(n)], [F(n), F(n-1)]], fib_fast(n) is a corner of the power. Check it against an iterative two-variable Fibonacci for every n <= 500. Check [[1,1,1],[1,0,0],[0,1,0]]^n against an iterative tribonacci for n <= 200, with the same mat_pow. Count the multiplies for n = 10^5 against the n - 1 of repeated multiplication. Then take F(100,000): compute its digit count from n * log10(phi) - log10(sqrt(5)), and confirm it by comparing with powers of ten (converting a huge int with str() raises ValueError past 4,300 digits by default, so avoid it). Time fib_fast(2^k) for k = 12..18 with best_of, printing the bit length of the answer, the time and the ratio to the previous row. State time, space and depth, and say why O(log n) multiplies is not O(log n) time.

Q59Every Way To BracketHard

"2-1-1" can be bracketed two ways, (2-1)-1 = 0 and 2-(1-1) = 2. Write split_tokens(text), a character loop that splits the expression into numbers and operators, then values_naive(text, calls) and values_memo(text), each with an inner ways(lo, hi) that returns the values of every bracketing of numbers lo..hi (inclusive): split at each operator, and combine every value on the left with every value on the right. A single number has one value. Write a naive version that counts its calls, and a version memoised on (lo, hi) with functools.lru_cache, whose cache_info() gives the misses and hits (the memo keeps results per range, and DSA Topic 21 fills the same ranges bottom-up in a table). The number of bracketings for m operators is the Catalan number comb(2m, m) // (m + 1). Print "2-1-1" and "2*3-4*5" with their sorted values. Check against an independent oracle that builds every fully bracketed string and evaluates it with a tiny hand-written evaluator (eval_bracketed), on 40 seeded expressions with up to 5 operators (counting exceptions as failures). For m = 0..10 print the Catalan count, the naive calls, and the memo's misses and hits, then time both for m = 10. State time, space and depth.

Q60The Price Of A CallMedium

Is recursion slow, or is it just limited? Sum the same 900 items three ways: a recursive rsum(a, i) (index passed, base case first), a while loop, and the built-in sum. Repeat each 2,000 times with best_of(fn, repeats=3) and print the cost per element in nanoseconds, then the ratios rsum / loop and loop / sum. Do it again for n = 100 (more repetitions, so the work stays comparable) and print the two rsum / loop ratios beside each other, so you can read from the numbers how the ratio changes with n. The point is that the call overhead multiplies the time of every element but not its O(n) growth, while the O(n) stack is the real limit: show rsum on 5,000 items raising RecursionError (print the type name) and the loop and sum finishing, and show the loop and sum on 10^6 items. Close with a comment about when recursion earns its place (branching and nested data). State time, space and depth, and a sentence for when you would not use recursion.

Q61Memoising Two ArgumentsMedium

Count the paths from the top-left to the bottom-right of a grid, moving only right or down, when some cells are blocked ("#") and the rest are open ("."). The state of a call is two numbers, (r, c), so the memo key is that pair. The grid itself is not part of the key: it lives in a closure, and make_counter(grid) returns a memoised paths(r, c) for that one grid. Write the naive paths_naive(grid, r, c, calls) and the function all_paths(grid, r, c, path, out), which builds every path as a list of cells and appends it to out, as the oracle that does not count at all. Fuzz the memoised count against len(out) on 300 seeded grids of 1 to 6 rows and columns with about 15% of the cells blocked (the start or end may be blocked, which gives 0 paths), counting exceptions as failures. Then show why the grid cannot be an argument of a cached function: pass it and print the exception type. On one 9 x 9 grid compare the naive call count with the number of distinct (r, c) states the cache holds, and on a 60 x 60 grid with seeded blocks (start and end open) print the number of paths, its digit count, the cache size and how many frames deep the recursion went. Name the table form: DSA Topic 21 fills the same states bottom-up. State time, space and depth.

Q62Integer PartitionsHard

A partition of n is a way to write it as a sum of positive integers where order does not matter, so 4 = 3 + 1 = 2 + 2 = 2 + 1 + 1 = 1 + 1 + 1 + 1 = 4 gives 5 partitions. Let p(n, k) be the number of partitions of n into parts that are each at most k. Either some part equals k (take it, leaving p(n - k, k)) or none does (p(n, k - 1)), so p(n, k) = p(n - k, k) + p(n, k - 1). Write parts(n, k), which returns every such partition as a tuple in non-increasing order using the same recurrence, and check it for every n from 0 to 20: the tuples are distinct, non-increasing, sum to n, and their number matches the known values 1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42, 56, 77, 101, 135, 176, 231, 297, 385, 490, 627. Write the memoised count p_count(n, k, depth, memo, stats) with an explicit memo dict, which records the deepest depth it reached, and print p(100), the number of memo entries and that depth. Show the naive call count for p(40) against the memo's, and show a student version whose base case forgets n < 0 and raises RecursionError (print the exception type). State time, space and depth.

Q63Recursive GeneratorsHard

A recursive function can yield from its recursive calls and so produce values one at a time. Write flatten_gen(x), which yields every non-list item of a nested list in order, and subsets_gen(a, i, chosen), which yields every subset of a as a tuple (include or exclude each item). Check them against eager versions that return lists, on 300 seeded nested lists and on every n up to 10. Measure with tracemalloc the peak memory of building all 2^16 subsets as a list against counting them while the generator runs, and the same for flattening 1,000 sublists of 100 integers. The generator holds one frame per level of nesting, so its memory is O(depth); the list holds the whole output. Then measure the cost that yield from hides: each value passes up through every enclosing generator, so with a chain-nested list (a list in a list in a list, 300 integers at the bottom) the time per value should grow with the depth. Time depths 100, 200, 400 and 800 with best_of, print the time per value and compare it with the eager flat_down on the same lists. Finally build a chain 1,500 deep with a loop and show that the generator still raises RecursionError (print the type). State time, space and depth.

Q64Inversions Per ElementHard

For each index i, count how many later values are smaller: counts[i] = number of j > i with a[j] < a[i]. The sum of counts is the total number of inversions. Write the O(n^2) double loop per_element_truth(a). Then write a divide and conquer that never reorders the list: carry (value, index) pairs in a fixed list items, and let solve(lo, hi) handle the half-open range [lo, hi): solve both halves, then call cross_count(items, lo, mid, hi, counts), which sorts copies of the two halves with sorted(), walks them with two pointers (DSA Topic 2's merge pointers) and, for each left pair, adds the number of strictly smaller right values to counts[its index]. State the recurrence, which is T(n) = 2T(n/2) + O(n log n) because of those sorts. Fuzz against the truth on 400 seeded lists of 0 to 40 values with many duplicates, counting exceptions as failures, and show the student bug of using <= instead of < in the walk: print the wrong counts for [2, 2, 1] beside the truth. Time the truth and the divide and conquer at 1,000 and 2,000 values, and the divide and conquer alone at 20,000. Name in a comment the O(n log n) version that returns each half already sorted (merge sort, DSA Topic 9). State time, space and depth.

Q65Divide And Conquer That LosesHard

An n x n matrix has every row and every column sorted ascending. To find a value x, write quad_search(a, x, r0, r1, c0, c1, calls) on the half-open region [r0, r1) x [c0, c1): look at the centre cell v. If v == x, return its position. If x < v, everything at or below and to the right of the centre is at least v, so discard that quadrant and search the other three. If x > v, everything at or above and to the left is at most v, so discard that quadrant and search the other three. One of four quadrants goes per step, so T(n) = 3T(n/2) + O(1), which is O(n^(log2 3)), about n^1.585. Fuzz it against a plain scan on 300 seeded matrices of 1 to 7 rows and columns (rectangular, with duplicates), searching every value from just below the smallest to just above the largest, counting exceptions as failures. Count calls on the matrix a[i][j] = 2 * (i + j) for n = 2, 4, ..., 1024 while searching the odd value 2n - 1, which lies between two diagonals and forces the search to follow the whole diagonal, and print the ratio of successive counts (it should approach 3). Compare with the staircase walk of DSA Topic 4 (start at the top-right, move left or down), which takes at most 2n - 1 steps, and time both at n = 512. Splitting in more pieces is not automatically a win. State time, space and depth.

Q66Gray Codes By ReflectionMedium

A Gray code lists all 2^n bit strings of length n so that neighbouring strings differ in exactly one bit. Build it by reflection: gray(0) is [""], and gray(n) is "0" placed in front of every code of gray(n - 1), followed by "1" placed in front of every code of gray(n - 1) read in reverse order. Write gray(n). Check for every n from 0 to 16 that all codes are distinct, that neighbours differ in exactly one bit, that the last code and the first also differ in one bit, and that the list equals format(i ^ (i >> 1), "0nb") for i = 0 ... 2^n - 1. Print gray(3) and gray(4). Show the student bug of forgetting to reverse: print gray_no_reverse(3) and the first neighbouring pair that differs in more than one bit. State the recurrence, the time (every code has n characters), the space and the depth, and count the calls.

Q67Phone Keypad WordsEasy

On a phone keypad 2 is abc, 3 is def, and so on up to 9 as wxyz (7 is pqrs). Given a digit string such as "23", list every letter string it could spell: one level of recursion per digit and one branch per letter on it. Write words(digits, i, prefix, out), which extends prefix by each letter of digits[i] and appends the finished word to out at the end of the digits. The empty digit string spells one word, the empty string, as itertools.product() of nothing yields one empty tuple. Print the nine words for "23". Check the number of words equals the product of the letter counts (3 or 4 per digit) and the list equals ["".join(t) for t in product(*letters)] for 200 seeded digit strings of length 0 to 7. Count the calls for "7979": the call count is the sum, over the levels, of the product of the choices so far. Show the student version words_bad whose base case is if not digits: return [], and print what it returns for "23" beside the truth. State time, space and depth.

Q68Pass Down Or Return UpMedium

A recursive function can build its output in two styles. Passing down: it receives one output list and appends to it. Returning up: each call builds and returns its own list, and its caller joins them. Write both for flattening, as flat_down(x, out) and flat_up(x, copies), where flat_up adds len(child) to the counter copies whenever it copies a child's list into its own. The returned lists make every item copied once per level that it rises through, so the number of copies equals the sum of the nesting depths of the items. Check that formula on a chain-nested list: at each of 600 levels four integers and then the next level ([0, 1, 2, 3, [0, 1, 2, 3, [...]]]). Compare it with a flat list of 2,400 items in a list. Time both styles on both shapes with best_of, and compare the tracemalloc peaks. Then do the same for subsets of 14 items: subsets_down(a, i, path, out) appends to one list, subsets_up(a, i, copies) returns r + [(a[i],) + s for s in r]. Count the list slots written per output subset for both. State which shape the returning style hurts, which it does not, and what you would pick. State time, space and depth.

Q69Subsets Without RecursionMedium

DSA Topic 1 enumerated subsets with a bitmask: every integer from 0 to 2^n - 1 is a subset, with bit i meaning "item i is in". Write subsets_mask(a) that way and subsets_rec(a, i, chosen, out) with include or exclude recursion. Print both for [1, 2, 3] to show the same subsets in a different order, and check the two produce the same set of tuples for every n up to 12. Time both at n = 16 and print the time per subset. Then change the question to one where a choice depends on the earlier one: count the subsets of n items with no two neighbouring items both chosen (the answer is a Fibonacci number). The mask version must still examine every one of the 2^n masks and test it with mask & (mask >> 1) == 0. The recursion can decline to choose item i + 1 after choosing item i, so it only ever builds valid subsets. Count masks examined and recursive calls at n = 20, check both give the Fibonacci number, and time both. Cutting a branch early because it can no longer succeed is called pruning; DSA Topic 19 builds it as a technique. Extrapolate how long the plain mask loop would take at n = 25 from the measured time per mask. State time, space and depth for each.

Q70When Recursion Is The Wrong ToolMediumMust Do

Measure six cases and give each one its fix. Label the code # STEP 1: through # STEP 6:. Step 1: a linear walk, rsum_to(i, n) adding the integers from i up to n, with n = 100,000: catch the exception and print its type, then fix it with sum(range(n)) and check the value is n * (n - 1) // 2. Step 2: naive two-call Fibonacci at n = 25, counting the calls (check they equal 2 * fib(26) - 1) and timing it against the two-variable loop. Step 3: recursion over slices (rsum_slice(a) returns a[0] + rsum_slice(a[1:])) on 900 items, counting the items copied (it must equal n * (n - 1) / 2) beside the index version, and timing both. Step 4: recursion where a formula exists: the number of right-or-down paths through a 9 x 9 step grid by the naive recursion, with its call count, against math.comb(18, 9). Step 5: summing 2^17 items by halves: it is fine, because the depth is the logarithm of the size; print the measured depth, the depth that 10^6 items would need (computed with math.ceil(math.log2(...))) and the limit. Step 6: nested JSON, the case where recursion is the right tool: count the values and the nesting depth in a seeded document of nesting at most 6, and check the explicit-stack version agrees. End with a table of the six cases: the symptom, the fix and whether recursion stays. State time, space and depth for each function.

Q71Base Cases That Are Never ReachedEasy

A base case only stops the recursion if every input actually lands on it. Here are three functions a student wrote, each with a base case that some input skips. down_by_two(n) stops at n == 0 and recurses on n - 2. factorial(n) stops at n == 0 and recurses on n - 1. halvings(x) counts how many times you can halve a float before it hits 0.0: it stops at x == 0.0 and recurses on x / 2. Run each one on inputs from -2 to 5 (for the first two) and on 1.0 (for the third). Catch RecursionError and print its type name beside each input. For halvings, count the halvings with a loop first: starting from 1.0, the float really does reach 0.0, so the base case is reachable. Explain why the recursion still fails. Then fix each one: use <= for the first, raise ValueError on a negative input for the second, and stop at a tolerance for the third. State time, space and depth.

Q72The Mutable Default AccumulatorMedium

A student writes collect(x, out=[]) to flatten a nested list into out, recursing into each sublist with the same out. The default list is created once, when def runs, and every call that leaves out out shares it. Call collect([1, [2, 3]]), then collect([4, [5]]), and print both results, whether the two results are the same object, and the first result again after the second call. Fix it with out=None. Then look at the same trick used on purpose: fib(n, memo={}) keeps its memo between calls. Count the calls made by fib(25) on a "cold" run, then again on a second run meant to measure the same thing, and print the memo's size between them (read it from fib.__defaults__). Show why this is fragile (state survives between unrelated calls, so the second experiment measures nothing), and give two clean fixes: a fresh memo per top-level call, and lru_cache with cache_clear(). State time, space and depth.

Q73The Memo That Remembers Too MuchHardMust Do

A memo is only correct if its key holds every input that can change the answer. Label the code # STEP 1: through # STEP 4:. In step 1, a student counts the ways to climb n stairs with a tuple of allowed step sizes, using a module-level memo keyed on n alone. Call ways(4, (1, 2)) and then ways(4, (1, 2, 3)), and print the second answer beside the truth from an unmemoised recursion. In step 2, a function reads a global: cost(n) is the cheapest way up n stairs when a 1-step costs 1 and a 2-step costs the global FEE. Compute cost(10) with FEE = 2, change FEE to 1, and print the stale answer beside the truth. In step 3, count_paths(grid) counts right/down paths around blocked cells using an inner function, but the memo keyed on (r, c) sits outside, so a second grid of the same size reuses the first grid's answers. Print both grids' answers beside the truth. In step 4, fuzz step 1's bug: seeded pairs of calls (reset the memo before each pair, then call twice and check the second call), keep every failing pair, and print the smallest one. Then fix all three: put every input in the key (a tuple of steps is hashable), pass the fee as an argument, and make one memo per grid. Fuzz the fixed ways the same way. State time, space and depth.

Q74lru_cache PitfallsHard

functools.lru_cache hides three traps beyond the hashable-argument rule met earlier in this topic. Show each with printed output. First, square(1) and square(n=1) are cached as two different entries in CPython: print cache_info() after square(1), square(n=1), square(1). Second, a cached divisors(n) returns a list, and a caller removes n from it to get the proper divisors; print the next caller's divisors(12) beside the truth. Fix it by returning a tuple. Third, bound the cache: decorate a naive-shaped Fibonacci with maxsize=1, 2, 3 and None, count how many times the body runs for fib(25), and print each count with cache_info(), beside the uncached count 2 * fib(26) - 1. Measure, don't assume: a cache of two looks like enough for Fibonacci. Then print the maxsize=2 body runs for n = 15, 20, 25, 30 and the ratio between neighbours, to see how that count grows. State time and space.

Q75Ackermann And The Depth HazardHardMust Do

Ackermann's function is three lines long: A(0, n) = n + 1, A(m, 0) = A(m - 1, 1), and A(m, n) = A(m - 1, A(m, n - 1)). It always terminates, yet its depth grows with its value. Label the code # STEP 1: through # STEP 4:. In step 1, write it recursively with a call counter and a maximum-depth counter, and print the value, calls and maximum depth for (1, 3), (2, 3) and A(3, n) for n = 3..6. In step 2, check the closed forms A(2, n) = 2n + 3 and A(3, n) = 2^(n+3) - 3 for n = 0..6. In step 3, show that A(3, 7) raises RecursionError (it needs more than 1,000 frames), then add a dict memo on (m, n) and measure what it really saves: print calls and maximum depth for the memoised A(3, n), n = 3..9, catching RecursionError. Does the memo remove the depth hazard, or only move it? In step 4, compute A(3, 7) with a list used as a stack (DSA Topic 10 teaches the stack): the stack holds the pending m values and n is the running value. Print the value and the number of loop steps, and check it against the closed form. Name A(4, 1) without computing it. State time, space and depth.

Q76Memoisation Does Not Fix DepthHard

A memo stops repeated work, but the first call still has to go all the way down. Write fib(n) with a dict memo and call it cold on n = 5000: catch the RecursionError and print its type name. Fix it two ways. First, warm the memo in increasing order (fib(0), fib(1), ..., fib(5000)), so each call finds n - 1 and n - 2 already stored; record the deepest depth any warming call reached and print it. Second, use the two-variable loop. Check that both give the same number and print its digit count. Then do the same cold experiment with @lru_cache(maxsize=None). The wrapper adds C-level work to every frame, so on some CPython versions it stops at a different depth from the dict memo. Probe the largest cold n each version handles (in steps of 10) and print only comparisons, never the exact numbers. State time, space and depth for each fix.

Q77Tail Calls And A TrampolineHard

The accumulator version earlier in this topic showed that a tail call (return fact_acc(n - 1, acc * n), nothing left to do after it) still costs a frame in CPython, which has no tail-call optimisation. Build the escape: a trampoline. sum_t(n, acc) returns either its answer or a zero-argument function (a thunk) that makes the next step, and trampoline(result) keeps calling while the result is callable. Sum 1..100,000 this way, check it against n * (n + 1) // 2, and print how many frames sat above the trampoline's caller at the base case, to show the stack stays flat. Do factorial the same way for n = 3000 and check against math.factorial. Time the trampoline against a plain loop on n = 100,000 with best_of, print the ratio, and say what the trampoline buys and what it costs. State time, space and depth.

Q78The Split That Never ShrinksHard

Divide and conquer only terminates if every part is strictly smaller than the whole. Two students write range_max(a) by halves. The first uses a closed range [lo, hi] with mid = (lo + hi) // 2 and recurses on [lo, mid] and [mid, hi] (the overlap does not hurt a max), with the base case lo == hi. The second uses a half-open range [lo, hi) with the same mid, recurses on [lo, mid) and [mid, hi), and has only the empty base case lo == hi. Trace by hand which range stops shrinking in each. Then fuzz both over list sizes 0..20 on seeded lists, catching RecursionError as a failure, and print the list of failing sizes and the smallest one. Size 0 goes through the function too: an empty list should give None. Fix each: the closed version recurses on [lo, mid] and [mid + 1, hi], and the half-open version adds a size-1 base case; both answer None for an empty range. Fuzz the fixes the same way. Connect this to DSA Topic 3's loop shapes. State time, space and depth.

Q79Exponential In DisguiseMedium

Two functions that look linear and logarithmic call themselves twice on the same input. rmax(a, i) returns a[i] if a[i] > rmax(a, i + 1), and otherwise returns rmax(a, i + 1), a second call that redoes all the work. power(x, n) returns power(x, n // 2) * power(x, n // 2), times x when n is odd. Count the calls of each. Use rmax on increasing, decreasing and seeded shuffled lists for n = 5, 10, 15, 20, and power(3, n) for n = 2^4, 2^8, 2^12, 2^14. Print the counts beside 2^n - 1 and 4n - 1, and beside the fixed versions, which store the call's result in a variable. Check every result against max and pow. Write the broken and fixed recurrences. State time and space.

Q80Cycles In Nested DataHard

A list can contain itself: a = [1, 2]; a.append(a). Show what three tools do with it: a naive recursive flatten (catch the RecursionError), repr (Python marks the cycle as [...]), and json.dumps (catch the ValueError and print its message). Then write find_cycle(x) that keeps a set of the id()s of the lists on the current path (DSA Topic 7's seen-set), adding an id on entry and removing it on exit, and reports a cycle when it meets an id already on the path. A part that appears twice is not a cycle: s = [3]; b = [s, s]. Show a student's version that never removes ids, so it calls b cyclic. Run all of them on four inputs (a self-cycle, a two-list cycle, a shared part, and a plain nested list) and print a table. Finish with safe_flatten, which raises ValueError on a cycle and flattens everything else. State time, space and depth.

Q81The Generator That Does NothingMedium

A recursive generator that flattens a nested list looks like the plain recursive flatten with yield swapped in. Write flat_bad(x), whose recursive step is the plain call flat_bad(part) inside a for loop, and show that a call to a generator function runs none of its body: it builds a generator object. Use a module-level list ran that each body appends to as it starts, so you can print how many bodies started against how many calls were made. Show list(flat_bad([1, [2, 3], 4])) beside the truth. Then show two more variants a student really writes: flat_ret, which does return [x] for a scalar inside a generator (the returned list ends up in StopIteration.value and the caller never sees it), and flat_gen, which does yield flat_gen(part) and so yields generator objects instead of values (print the type names). Fix all three with yield from and yield x. Fuzz the four versions against a plain list-returning flatten on 300 seeded nested lists, counting exceptions as failures, and explain from the counts which inputs hide the bug. State time and space, including what yield from costs per value.

Q82The Wrong Combine StepHard

In divide and conquer the two recursive calls are usually right and the bug hides in the step that combines them. Write two buggy combines and fix each. First, the maximum subarray by halves (the best subarray is in the left half, in the right half, or crosses the middle), where the crossing part starts its running best at 0, which quietly allows an empty suffix and an empty prefix, so an all-negative input returns 0. Second, an inversion count (pairs i < j with a[i] > a[j]) whose crossing step uses >= instead of >, so equal values are counted. The crossing step for inversions sorts copies of both halves with sorted() and walks them with two pointers (cross_count); this is O(n log n) per level, and a comment names the faster version that returns each half already sorted, which is merge sort (DSA Topic 9). Both functions raise ValueError on an empty list (the oracle too, so empty input is part of the fuzz, with sizes 0 to 8); the fuzz compares outcomes, a value or an exception name. Fuzz each buggy version and each fixed version against an O(n^3) brute force on seeded inputs, and show that the failure count of the first bug equals the number of all-negative lists of length 2 or more. Then find the minimal failing input by trying every list over a tiny alphabet in order of length, and print it. Finally show that a generator that only makes positive values, or only distinct values, passes the buggy versions, so the test data has to be able to reach the bug. State time and space.

Q83Recurrences MisreadHard

Four recurrences look like something you have solved before and are not. Evaluate each with a memoised or plain recursive function of n (never by expanding every call), write the recursion-tree argument as a comment, and print measured numbers that settle the answer. (1) T(n) = 2T(n/2) + n log2 n looks like master-theorem case 3 (f(n) is bigger than n, so "O(n log n)"), but f(n) is not polynomially bigger than n^(log_2 2) = n, so no case applies; the tree gives O(n log^2 n). Print T/(n log2 n), which keeps growing, and T/(n log2^2 n), which settles, at n = 2^10, 2^15, 2^20, 2^25, and the work on each level for n = 64. (2) T(n) = T(n/2) + T(n/4) + n has two different subproblem sizes, so the master theorem does not fit; level sums shrink by 3/4 each level, so T(n) = O(n). Print T(n)/n and the first level sums. (3) T(n) = 2T(n/2) + n / log2 n has a driving term smaller than n, but again not polynomially smaller, so the master theorem's first case does not apply and "O(n)" is wrong; the tree gives O(n log log n). Evaluate it for n = 2^k and print T/n for k = 10, 20, 40, 80, 160, with the gain each time k doubles. (4) T(n) = T(sqrt n) + 1 shrinks the size by a square root, not a fraction, so there is no b; substituting n = 2^m turns it into S(m) = S(m/2) + 1, so T(n) = O(log log n). Evaluate it with math.isqrt for n = 2^(2^j) and print T, log2 n and log2 log2 n. Check each closed form where one exists. State time and space for the evaluators.

Q84The Strip Cut ShortHard

Closest pair of points in the plane, by divide and conquer: sort by x once with sorted(), split at the middle, find the best squared distance d2 in each half, and then check the strip of points within d of the dividing line, sorted by y, comparing each point with the points above it until their y-gap is at least d. Write closest_pair(points, window=None, sort_strip=True) where window caps how many later strip points each point is compared with (None is the correct scan) and sort_strip=False leaves the strip in x order. Use integer coordinates and compare squared distances so that no float is involved. Fuzz window = 1, 2, 3, 7 and the unsorted strip against the O(n^2) brute force on 1,000 seeded uniform sets and 1,000 seeded dense-grid sets (counting exceptions as failures), print the failure counts, and shrink the first failing input of two variants to a minimal point set by deleting one point at a time while it still fails. Then print a hand-built four-point set where a window of 2 is wrong and 3 is right. Argue why 7 is enough with the packing argument (a 2d by d box cut into squares of side d/2), computing the numbers you quote. State time and space, and say honestly what the fuzz did and did not find.

Q85The Suite That Catches All Of ItHardMust Do

Build one differential test harness that catches eight recursion bugs by name. Each case has a buggy function, a fixed function, an independent oracle and a seeded input generator: an unreachable base case (a countdown that never stops for negative input), a mutable default accumulator that leaks between calls, a memo keyed on n alone for a function that also depends on k, a function that calls itself twice instead of once (caught by a call budget that raises BudgetExceeded), a closed-range split that never shrinks, an inversion count with the wrong combine step (>=), a flatten that loops forever on a cycle, and a generator that forgets yield from. A guarded run(fn, *args) turns every call into an outcome, ("ok", value) or ("err", exception name), so RecursionError and the budget count as outcomes, not crashes. For each case compare the buggy and fixed functions with the oracle on the same inputs, in order, because two of the bugs are state bugs. Print one table row per bug with the number of inputs on which the buggy version differs, the kinds of failure seen, and the number of inputs on which the fixed version differs (it must be zero). Use # STEP 1: labels and do not mention question numbers.

Q86The Nested Data ToolkitMini-ProjectMust Do

Build a small toolkit for nested data made of lists, dicts with string keys, and the scalars int, str, bool and None: validate, flatten, depth, paths, get, set_, deep_copy, deep_equal and map_leaves. Every function that walks the data validates it first and raises TypeError for an unsupported type (a tuple, a set, a float, a dict with a non-string key) and ValueError for a cycle, where a part that is shared twice but does not contain itself is not a cycle. get and set_ take a path tuple and raise KeyError, IndexError or TypeError by the step that fails. The deep walkers (validate, flatten, depth, deep_copy, deep_equal) get explicit-stack twins, written with a list used as a stack (DSA Topic 10 teaches the stack). Fuzz the toolkit on 300 seeded random structures against copy.deepcopy, == and a json round trip, and by properties that need no second implementation (flatten agrees with paths and get; depth agrees with the longest path; a recursive function and its twin agree). Check the exception classes on structures with one defect inserted, and compare get with set_ on random bad paths. Then build a 100,000-deep structure with a loop: the recursive versions fail with RecursionError (print the type) and the twins finish. Use # STEP 1: labels and do not mention question numbers. State time and space for each function, including what a wide input does to the explicit stack.

Q87The Combinatorics GeneratorMini-Project

Build a small library of recursive generators: subsets(items), permutations_of(items) (items may repeat, and each distinct order appears once, in sorted order), combinations_of(items, k) (taking the first item or skipping it, stopping when k == 0 or too few items remain: the simplest pruning, which DSA Topic 19 develops), gray_code(n) (reflection) and partitions(n) (parts in non-increasing order). Each public function validates its input when it is called, not when the first value is requested, which means returning an inner generator from a plain function (show the difference with a generator that validates inside its body). Check every count by formula and against itertools (2^n, n!/(c1! c2! ...), math.comb, 2^n, and the partition numbers 1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42, 56, 77, 101, 135, 176, 231, 297, 385, 490, 627 for n = 0..20). Add perm_rank(p), the position of a permutation of distinct items among all permutations in sorted order, and its inverse perm_unrank(items, r), both recursive, built on the factorial number system (i * (m - 1)! for the item with i smaller items still unused). Check that the i-th permutation from the generator has rank i for every n up to 7, that unrank(rank(p)) == p for random permutations of 25 items, and that rank(unrank(r)) == r for random r below 20!. Check exception classes on bad input. The recursion is as deep as the input is long, so every function refuses more than 500 items with ValueError (show combinations_of(range(1100), 1) and a 1,500-item perm_rank refused, and a 300-item round trip that works). State time and space for each, and the depth.

Q88The Memo DecoratorMini-ProjectMust Do

Write your own memoize(maxsize=None) decorator, built with functools.wraps. The cache is a dict keyed by the argument tuple (keyword arguments are added after a marker object, in the order given, as lru_cache does), with hits and misses counters, cache_info() and cache_clear(). With a maxsize, evict the least recently used entry using only dict order (DSA Topic 7): on a hit, pop the key and put it back at the end; on a miss with a full cache, delete next(iter(cache)). Insert only after the function returns, and treat maxsize=0 as "never store". Validate maxsize (an int or None, not negative) and let an unhashable argument raise TypeError before anything is counted (except with maxsize=0, where nothing is hashed, as in lru_cache). Check it against functools.lru_cache for the same hits, misses and currsize on Fibonacci, grid paths and integer partitions with maxsize of None, 16 and 64, and fuzz it on 400 seeded random calls (positional, keyword and unhashable) for five maxsize values, comparing results, cache_info() after every call and the number of times the underlying function ran (counting exceptions as failures). Show why decorating the name sends the recursive calls through the cache, and what happens when you wrap a function under a different name. Time warm lookups against lru_cache with best_of and print the numbers without a verdict. Use # STEP 1: labels and do not mention question numbers.

Q89The Call TracerMini-Project

Write a decorator trace(fn), built with functools.wraps, that records every call: the arguments (shortened with repr to 24 characters), the depth, and the return value or the exception name (re-raising the exception, and restoring the depth in a finally). The wrapper carries show(limit=40), which prints the call tree indented by depth and stops at limit lines with a count of the rest, report(), which returns the number of calls, the maximum depth in frames, the number of distinct argument sets and the number of repeated calls (calls minus distinct), reset() and depth(). trace of a non-callable raises TypeError. Because the decorator replaces the name, the recursive calls inside the function go through it too. Run it on four workloads: fib(5), fast power x^13, Tower of Hanoi for 3 disks, and the divide-and-conquer maximum subarray on 5 values (with the list in a closure so that the arguments are (lo, hi)). Print each call tree, then a table of the four reports with each call count checked against its closed form (2 * fib(n + 1) - 1, bit_length + 1, 2^n - 1, 2m - 1), and name from the numbers which workloads repeat work. Show show(limit=5) on fib(6). Fuzz that tracing changes nothing: results equal the untraced reference, and a function that raises keeps its exception class and leaves depth() at 0 (counting exceptions in the harness as failures). State time and space.

Q90Tower Of Hanoi, CompleteMini-Project

Build a complete Tower of Hanoi toolkit. (1) A recursive solver that returns the list of moves (disk, from_peg, to_peg) and validates n (an int from 0 to 20, else TypeError or ValueError). (2) A legality simulator, simulate(n, moves), that raises ValueError naming the first illegal move (the disk is not on top, or it lands on a smaller disk) and otherwise returns the pegs. (3) ASCII drawing of the pegs for n = 3 at the start, after the largest disk moves, and at the end. (4) The iterative solution: the smallest disk moves one peg in a fixed cycle on every odd move, and every even move is the only legal move that does not touch the smallest disk. Match the iterative moves against the recursive ones move for move for n = 0..16, check the count 2^n - 1, and run the simulator on every one up to 12; time both for n = 16 with best_of and print the numbers. (5) Four pegs: the Frame-Stewart count F(n) = min over k of 2F(k) + 2^(n-k) - 1, memoised, for n up to 10, compared with 2^n - 1, and a real four-peg solver that parks the k smallest disks on a spare peg using all four pegs, moves the rest with three, and brings the k back, whose moves are simulated on four pegs and counted against F(n). Finally fuzz the simulator: change one move of a valid solution (counting any exception other than ValueError as a failure) and check it never ends up solved. State time and space.

Q91The Directory WalkerMini-Project

A folder's size is the size of its own files plus the sizes of its subfolders, which is a recursive definition, so a disk-usage tool is a recursion over folders. Build one in a sandbox. Create a tempfile.mkdtemp() folder and fill it with seeded nested folders (random.Random(8), short names d0, d1, ..., at most 6 folders deep) holding files of seeded sizes. Write du(path, rel, sizes), which uses os.scandir, sorts the entries by name so the order is fixed, recurses into each subfolder, records every folder's total in sizes under a path like ./d0/d1, and returns the total. Check every total against a second answer built from os.walk(root, topdown=False), which visits children before their parents. Then report the deepest folder (ties broken by the smaller path), the five largest folders with an explicit tie-break, and the number of folders at each depth. Finish with du_stack, the same totals from a list used as a stack (DSA Topic 10 teaches the stack) with a processed flag, checked equal. Remove the sandbox at the end and print that it is gone. State time, space and depth.

Q92The Ranking ComparerMini-Project

Two judges rank the same films. How far apart are they? The Kendall tau distance counts the pairs of films the judges order differently. Read judge A's list, replace each film with its position in judge B's list, and the disagreeing pairs are exactly the inversions of that sequence. Write count_disputes(seq, lo, hi, disputes), a divide-and-conquer inversion counter that sorts copies of both halves with sorted() and walks them with two pointers in a helper named merge_count (DSA Topic 2 merged two sorted arrays). It must also add, for every item, the number of disagreeing pairs it is part of: later items that are smaller, plus earlier items that are larger. Fuzz it against an O(n^2) brute force on 300 seeded permutations, checking both the count and every per-item number, and check that the per-item numbers add up to twice the count. Then compare: eight films ranked by two judges (distance, normalised by C(n, 2), and the three most disputed films with a tie-break), and seeded rankings of 50 items: identical, after 1, 10 and 100 random adjacent swaps, reversed and shuffled. Explain why k adjacent swaps can create at most k disagreements. Time both counters at n = 2,000. State time, space and depth.

Q93Karatsuba MultiplicationMini-Project

Multiplying two n-digit numbers by hand takes n^2 single-digit products. Can divide and conquer do better? Store a number as a list of base-10 coefficients, lowest digit first, and let sums of coefficients grow past 9 (carry them once, at the end). Write three multipliers that count their base-case products: schoolbook (every digit times every digit), four_split (split each number into a low and a high half: four half-size products, so T(n) = 4T(n/2) + n) and karatsuba (three half-size products, using (a0 + a1)(b0 + b1) - a0*b0 - a1*b1 for the middle term, so T(n) = 3T(n/2) + n). Check every product against Python's * after the carry pass, on random numbers of 2^4 to 2^10 digits and on 60 seeded pairs of unequal lengths padded with zeros. Count the base products, run the 4-split and schoolbook only up to 128 digits, and get the larger counts from a memoised count function. Show how the gap grows with n, and say what CPython's own int multiply does. State time, space and depth.

Q94The Fractal PrinterMini-Project

A fractal is a picture made of smaller copies of itself, so a recursive function draws it with one call per copy. Draw two in ASCII to depth 4. The Sierpinski triangle: the level-0 picture is /\, and a level-k picture is three level-(k - 1) pictures, one centred on top and two side by side underneath. Write draw(k, row, col), nested inside sierpinski(k) and writing into its canvas (a grid of characters) with three recursive calls, and check its output against a second version that builds the picture as a list of lines from the level below. The Cantor set: draw a bar of width 81, then recurse on its first and last thirds one row lower, to depth 4. Before running, predict from the recurrences: Sierpinski calls T(k) = 3T(k - 1) + 1, the number of / characters 3^k, the canvas 2^k rows by 2^(k+1) columns; Cantor calls 2^(K+1) - 1, segments 2^k on row k, filled characters 2^k * 3^(K-k) on row k. Print both pictures, then a table that checks every prediction for k = 0..7. State time, space and depth.

Q95The Recurrence WorkbenchMini-Project

Build a workbench that takes a recurrence T(n) = a T(n/b) + n^c and tries to falsify the master theorem's prediction, not merely agree with it. For each recurrence, evaluate T(n) exactly with evaluator(a, b, c), a memoised function of n (T(1) = 1, not stored), so even 7T(n/2) at n = 2^20 stores 20 values instead of making 7^20 calls. Predict with the theorem by comparing a with b^c as integers, with no floats: a < b^c means the top level wins (n^c), a == b^c means every level ties (n^c log n), and a > b^c means the bottom level wins (n^(log_b a)). Evaluate every row at n = b^20. Fit the growth exponent from the last step, log(T(n) / T(n/b)) / log(b). Then compute the settle score |r(n) / r(n/b) - 1|, where r is T divided by a candidate form. Accept a form only if its exponent gap is under 0.25 and its settle score is under 0.02. Test two forms per row: the prediction, and a rival that differs only by one log factor (the log dropped on a tie row, added on any other row). The workbench must accept every prediction and reject every rival. Run eight recurrences: 3T(n/3) + n, 9T(n/3) + n^2, 4T(n/2) + n^2, 2T(n/4) + 1, 8T(n/2) + n^2, 7T(n/2) + n^2, 2T(n/2) + n^2 and 3T(n/4) + n. Print one table, with every verdict computed from the printed numbers. State time and space.

Q96Explaining It ColdInterview

An interviewer says: "Explain recursion to me, and show me, don't tell me." Give a short answer in four parts, each backed by a few printed lines from code you write on the spot. (1) The base case and the recursive case, on Euclid's gcd(a, b) = gcd(b, a % b): print an indented trace of gcd(89, 55) and say why the argument always gets closer to b == 0. (2) The call stack and its limit: show how many frames that trace held at once, print sys.getrecursionlimit(), and run a one-step-at-a-time length(s, i) on 500 characters (fine) and 5,000 characters (RecursionError, caught). (3) Memoisation, on the Catalan numbers C(n) = sum of C(i) * C(n - 1 - i): count the calls without a memo (predict 3^n) and with a dict memo (predict n(n + 1) + 1), and check the value against comb(2n, n) // (n + 1). (4) Divide and conquer and the master theorem: find the minimum and maximum of a list by halves, count the comparisons (predict 3n/2 - 2 for n a power of 2, against 2n - 2 for one scan), and state the case of the master theorem. End with the follow-up questions you expect and the later tool for each. State time and space for every function.

Q97Diagnosing By ReasoningInterview

The interviewer pastes five short recursive functions and asks: "Which input breaks each one, and what happens? Say it before you run it." Write each prediction down as data first (the input and the exact result, exception name or count you expect), then run the code and print whether the prediction held. The five: count_digits(n) with if n == 0: return 0 as its only base case; find_path(d, key, path=[]), which returns the list of keys leading to key in a nested dict; count_vowels(s), which recurses on s[1:] (predict the number of characters copied for 300 and 600 characters); depth(x) for nested lists, which calls depth(part) once in its if and again to store the new best (predict the calls on a flat list of 1,000 numbers and on a chain nested 18 deep); and decode(s, i), the number of ways to read a digit string as letters (1 to 26), memoised in a module-level dict keyed on i. Then fix each one and show the fix passing on the input that broke it. State time and space of every fix.

Q98Recursion, Stack Or LoopInterview

Three workloads arrive and the interviewer asks which tool you would use for each: plain recursion, a list used as a stack (DSA Topic 10 teaches the stack), or a loop. Decide from measurements, not from taste. The workloads: (a) a JSON-like document nested 50,000 levels deep, where every level is {"v": i, "kids": [deeper, leaf]} (built with a loop); sum every "v". (b) Every way to climb 22 stairs in steps of 1 or 2, listed as tuples. (c) A version history of 200,000 versions where parent[v] is the version it came from; find how far the newest version is from the first. Write one iterative shape probe that measures the maximum depth and the maximum number of children per item, and a rule that picks a tool from those two numbers and the recursion limit. Then run the recursive version and the chosen tool on each full workload, catching RecursionError, and time both on a shallow copy of each workload so the cost of the choice is visible. Print the decision table. State time and space.

Q99The Mock InterviewInterview

Mock interview, round two. The opening question is the one from this topic: implement pow(x, n) in O(log n) multiplications, by recursion. Then the interviewer keeps pushing. Answer each follow-up with code and a printed check. (1) "Negative n?" Return an exact Fraction, check against Fraction(x) ** n, and say what pow(0, -1) must do. (2) "Under a modulus?" Reduce after every multiply, and check against pow(x, n, m) on seeded inputs. Mention what pow(3, -1, 7) means in Python 3.8+. (3) "Without recursion?" Read the bits of n from the lowest up, and count multiplies for both versions on several n. (4) "In C?" Simulate 64-bit unsigned products and show that pow under a modulus breaks when the modulus is near 2^61, because the product before the % needs 122 bits. (5) "Fibonacci in O(log n)?" Matrix power of [[1, 1], [1, 0]] is the known answer (this topic, fast power on matrices); give the fast-doubling identities F(2k) = F(k)(2F(k + 1) - F(k)) and F(2k + 1) = F(k)^2 + F(k + 1)^2, count multiplies for both, and compute F(10^18) mod (10^9 + 7) two ways. State time and space for each.

Q100CapstoneInterviewMust Do

Build an expression engine, the whole topic in one program. Label the code # STEP 1: through # STEP 6:. In step 1, tokenise arithmetic text with integers, single lowercase letters as variables, + - * and brackets, using a character loop. Parse it into nested lists such as ['-', ['*', 2, ['+', 3, 4]], 5] with three mutually recursive functions: an expression is terms joined by + or -, a term is factors joined by *, and a factor is a number, a variable or a bracketed expression. Also write to_text, which prints a nested list fully bracketed. In step 2, evaluate under an environment dict twice: recursively, and in post-order with a list used as a stack (DSA Topic 10 teaches the stack) and a processed flag. In step 3, simplify recursively: fold a part whose two sides are numbers, drop * 1, + 0 and - 0, and turn * 0 into 0 (every variable is a number here). In step 4, memoise repeated subexpressions: freeze the nested lists into nested tuples and evaluate with a dict keyed by those tuples, counting hits and misses. In step 5, fuzz 400 seeded expressions (nesting at most 6) and check six things: the recursive value equals Python's eval on the text, the stack value and the memo value equal the recursive one, the simplified expression has the same value and no more parts, and parsing to_text(tree) gives the tree back. Count crashes as failures. In step 6, build a 10,000-deep expression with a loop (the parser cannot build it from bracketed text: show that too), show the recursive evaluator raising RecursionError and the stack finishing it, then run a table over six workloads. State time, space and depth for every function.

Stuck? Solve it with a mentor.

Your first 1-on-1 session is free.

Book my free session