Recursion
IntermediateLesson 2 of 10 in Data Structures and Algorithms Course
What you will learn
- Recognize how a function that calls itself solves a problem through smaller versions of the same problem, and design recursive functions that are correct and always stop.
- Identify the base case and the recursive caseExplain what makes a function recursive, name its base case and recursive case, and check that every call moves toward a base case.
- Design a recursive function step by stepTurn a problem into a recursive solution: choose what makes an input smaller, solve the smallest inputs directly, and trust the recursive call to solve the rest.
- Identify the base case and the recursive case
- Follow how recursive calls run and return on the call stack, draw recursion trees for functions that call themselves more than once, and estimate the time and memory a recursive algorithm needs.
- Trace a recursive function on the call stackFollow the stack frames a recursive function creates, predict what it prints and returns, and explain recursion depth and stack overflow.
- Draw recursion trees for functions with several recursive callsRepresent every call as a node in a recursion tree, read off the order in which calls run, and spot work that is repeated.
- Estimate the running time and memory of recursive algorithmsWrite a recurrence for the work a recursive function does, sum it with a recursion tree for the common patterns, and state time and stack space in Big-O notation.
- Trace a recursive function on the call stack
- Break strings and lists into a first element and the rest, or into nested parts, and write recursive functions that process, search, build and generate them.
- Process strings recursivelySplit a string into its first character and the rest, and write recursive functions that measure, count, reverse and test strings.
- Process flat and nested lists recursivelyWrite recursive functions that sum, search, filter and transform lists, and use recursion to handle lists nested to any depth.
- Generate all subsets, sequences and permutationsUse recursion that branches into several calls to list every combination of choices, and predict how many results there are and how fast that number grows.
- Process strings recursively
- Split a problem into smaller parts, solve the parts recursively and combine their results, as in recursive binary search, fast exponentiation and merge sort.
- Apply divide and conquer to searching and powersRecognize the divide, conquer and combine steps, and write recursive binary search and fast exponentiation that shrink the problem by half each time.
- Sort a list with merge sortTrace merge sort on a list, write its merge step, and explain why it takes O(n log n) time and how much memory it uses.
- Apply divide and conquer to searching and powers
- Convert between recursive and iterative solutions, judge which one suits a problem in Python, and speed up recursion that repeats work by storing results.
- Compare recursion with iteration and convert between themRewrite recursive functions as loops and loops as recursion, recognize tail recursion, and choose the approach that fits the problem and the language.
- Speed up recursion with memoizationCache the results of recursive calls so each distinct subproblem is solved once, use Python's built-in caching decorators, and know when caching helps and what it costs.
- Compare recursion with iteration and convert between them
Recursion study guide
1Build a recursive solution
A recursive function solves a problem by asking for answers to smaller versions of that problem. The design starts with what the function must return, the inputs it can answer directly, and a change that brings every call closer to one of those inputs. Factorials, digit sums, and Towers of Hanoi show how a small amount of code can express both a simple calculation and a plan with several stages.
1.1 Base cases, smaller inputs, and returned values
Recursion solves a problem through smaller instances of the same problem. A function is directly recursive when it calls itself. In mutual recursion, two or more functions call one another in a cycle. Either form needs a route to an answer that requires no further recursive calls.
Give the smallest input an answer
A base case answers an input directly. A recursive case gets an answer for a smaller input and uses it to construct the current answer. Factorial gives a clear example: and for positive integers.
def factorial(n):
if n < 0:
raise ValueError("n must be non-negative")
if n == 0:
return 1
return n * factorial(n - 1)
For integer inputs, factorial(4) asks for factorial(3) and waits to multiply by 4. The smaller calls ask for 2, 1, and finally 0. The base case returns 1, so the returned values are 1, 1, 2, 6, and 24. Multiplying the base answer by zero would make every larger factorial zero; the base answer must fit the operation that builds the result.
The sum from 1 through n has a different base answer: sum_to(0) is 0, and the recursive case is return n + sum_to(n - 1). Thus sum_to(4) becomes 4 + 3 + 2 + 1 + 0 = 10.
Check the direction of every call
A size measure tells you what gets smaller: a non-negative integer, a string's length, or the number of unprocessed list elements. In factorial, n - 1 moves a positive integer toward zero. Calling factorial(n) leaves the problem unchanged. Calling factorial(n + 1) moves away from zero.
Reaching a base case matters for every valid input. A negative starting value with repeated subtraction never reaches zero, which is why the function rejects negative inputs before recursing. A base case can be present in the code and still be unreachable.
Keep every needed base case
Fibonacci uses two smaller answers: . Its base cases are and . If only zero stopped the recursion, a call on 1 would also call on -1 and keep moving downward. For non-negative integer inputs, if n < 2: return n handles both starting values.
Pass the answer back
Writing factorial(n - 1) on a line by itself discards its answer. If execution then reaches the end of the function, Python returns None. A caller waiting to compute n * None raises TypeError. Printing a value also does not return it: use return to carry the computed value to the caller.
Mutual recursion follows the same rules. Let is_even(0) return True and is_odd(0) return False; otherwise each calls the other with n - 1. For is_even(4), the chain is is_odd(3), is_even(2), is_odd(1), is_even(0). The final True travels back unchanged through the waiting calls.
Key Takeaways
- A base case returns an answer without a recursive call.
- A recursive case must use smaller answers to build and return its own answer.
- Every valid input must reach a base case; reject invalid inputs before recursing.
- Two-step dependencies such as Fibonacci can require more than one base case.
- Mutual recursion must make progress just as direct recursion does.
1.2 Design the smaller problem before tracing the calls
Start by stating what one call promises to return. Then decide what makes another call a smaller version of that same task. While designing the recursive case, use the smaller call's promised answer; tracing the whole computation comes afterward.
A five-step design method
- Choose a size measure.
- Give the smallest valid inputs direct answers.
- Assume the function solves smaller inputs correctly.
- Combine those smaller answers into the current answer.
- Check that every call chain reaches a base case.
Step 3 is the recursive leap of faith. It lets you focus on one level: if the smaller answer is correct, does your combination produce the answer you promised? Together with correct base cases and termination, this explains why the whole function works.
Build a digit sum
For a non-negative integer, use the number of digits as the size measure. A single digit is already its own digit sum. For a longer number, % 10 takes the last digit and // 10 removes it.
def sum_digits(n):
if n < 0:
raise ValueError("n must be non-negative")
if n < 10:
return n
return n % 10 + sum_digits(n // 10)
For 4096, the first step adds 6 to the digit sum of 409. The next steps add 9 to the digit sum of 40, then 0 to the digit sum of 4. The base answer is 4, giving 4, 13, and finally 19 on return. The recursive call solves a digit-sum problem at every stage; it never changes into a different task.
Shrinking can use more than subtraction
Euclid's greatest-common-divisor algorithm returns a when b == 0; otherwise it returns gcd(b, a % b). For non-negative integers with positive b, the remainder is smaller than b. The chain gcd(48, 18) → gcd(18, 12) → gcd(12, 6) → gcd(6, 0) therefore stops and returns 6.
Choose the smallest valid input carefully. For a non-negative exponent, power(x, 0) must return 1. A function that stops only at exponent 1 misses zero and then subtracts into negative exponents.
Plan Towers of Hanoi with one smaller solution
Move a stack of disks between three pegs, one disk at a time, never putting a larger disk on a smaller one. To move n disks from a source to a target:
- Move the top
n - 1disks to the spare peg. - Move the largest disk from source to target.
- Move the smaller stack from spare to target.
With zero disks, do nothing. The two recursive calls have different peg roles. For 3 disks from A to C using B, the moves are A→C, A→B, C→B, A→C, B→A, B→C, A→C. That is 7 moves; the general count is .
Carry state in parameters
An extra position or running total belongs in a parameter. For example, count_vowels(s, i=0) can advance i + 1 while callers supply only the string. A helper can hide this extra state from the public function.
Test the base case before making the smaller call. Return computed answers instead of collecting them in a global variable, whose old contents can survive into the next call. Keep input() and presentation outside a function whose job is to compute a value.
Key Takeaways
- Design one call around its promised answer, its smallest inputs, and its size measure.
- The recursive leap of faith uses a smaller correct answer to design the current step.
- A remainder, a shorter sequence, or a smaller stack can provide progress.
- Hanoi requires two smaller moves with different peg roles and one largest-disk move.
- Helper parameters carry positions or running totals without global state.
- Test the base case before recursing.
2Follow calls and measure their cost
A short recursive expression can create many calls, and each call can leave work waiting. The call stack shows what is active at one moment; a recursion tree shows all calls made over the computation. Following both views makes output order, returned values, running time, and memory use easier to separate. The cost analysis also includes Python operations such as slicing, which can do much more work than one line suggests.
2.1 The call stack and the work that waits
The call stack records calls that have started and not yet returned. Each call adds a stack frame holding its parameters, local variables, and the place where its caller should continue. The newest frame finishes first: the stack is last in, first out.
Keep each call's state separate
In factorial(4) and factorial(3), the parameter named n belongs to a different frame. The outer frame still has 4 while the inner one has 3. A call does not overwrite its caller's local bindings. If a parameter refers to a mutable object, however, several frames can still refer to that same object.
Calling factorial with the zero base case creates frames for 4, 3, 2, 1, and 0. These five calls form the winding phase. Each non-base frame waits to multiply its own n by the returned smaller factorial.
| Call | Work waiting | Return value |
|---|---|---|
factorial(4) | 4 times the inner answer | 24 |
factorial(3) | 3 times the inner answer | 6 |
factorial(2) | 2 times the inner answer | 2 |
factorial(1) | 1 times the inner answer | 1 |
factorial(0) | No multiplication | 1 |
The unwinding phase begins when the base call returns 1. Then factorial(1) computes 1 × 1, factorial(2) computes 2 × 1, factorial(3) computes 3 × 2, and factorial(4) computes 4 × 6. The table's return column is filled from bottom to top.
Statement position controls output order
def show(n):
if n == 0:
return
print("enter", n)
show(n - 1)
print("leave", n)
show(3) prints enter 3, enter 2, enter 1, then leave 1, leave 2, leave 3. Work before the call runs during winding; work after it waits for unwinding. Each frame resumes immediately after its own recursive call.
For a numerical trace, sum_list([4, 7, 1]) leaves 4 + …, 7 + …, and 1 + … waiting before sum_list([]) returns 0. The returns are then 1, 8, and 12. Record the pending operation as well as the arguments so you do not accidentally add a value twice.
Depth measures simultaneous frames
Recursion depth is the largest number of frames of the recursive function active at once. Factorial on n with a zero base case has depth , including the initial and base calls. Stack memory is needed even when the final answer is small.
CPython normally starts with a recursion limit of 1000; sys.getrecursionlimit() reports the current setting. Excessive depth raises RecursionError, whether caused by an unreachable base case or a long valid chain. In an ordinary shallow caller, sum_to(900) returns 405,450, but sum_to(5000) exceeds the default limit. Java reports excessive stack depth with StackOverflowError.
A failure on a small input points to a progress or base-case bug. A failure only on a very long sequence can call for a loop. Raising the recursion limit too far can crash the interpreter; it is not a routine repair for recursive code.
Key Takeaways
- Each call has its own frame and local bindings.
- Trace the arguments, pending operation, and return value for every call.
- Work before a recursive call runs during winding; work after it runs during unwinding.
- Recursion depth counts simultaneous frames, including base calls.
- A valid but deep chain can raise
RecursionError.
2.2 Recursion trees show every call
A recursion tree draws one node for every call. The original call is the root. A call's children are the calls it makes directly, and base calls are leaves. Unlike the stack, the tree preserves calls that have already finished as well as calls still to come.
Read the branching pattern
| Pattern | Calls made by a recursive case | Examples |
|---|---|---|
| Linear recursion | One | Factorial, summation, binary search |
| Binary recursion | Two | Fibonacci, merge sort, Hanoi |
| Multiple recursion | More than two | Permutations at larger input sizes |
Linear describes the number of child calls, not necessarily linear time. Binary search has one child at each step but logarithmic time. A function that makes two child calls runs them in sequence unless it explicitly uses parallel execution.
Expand Fibonacci without merging nodes
For fib(n), return n when n < 2; otherwise return fib(n - 1) + fib(n - 2). The first levels for fib(5) are:
fib(5)
├─ fib(4)
│ ├─ fib(3)
│ │ ├─ fib(2)
│ │ │ ├─ fib(1)
│ │ │ └─ fib(0)
│ │ └─ fib(1)
│ └─ fib(2)
│ ├─ fib(1)
│ └─ fib(0)
└─ fib(3)
├─ fib(2)
│ ├─ fib(1)
│ └─ fib(0)
└─ fib(1)
There are 15 nodes: arguments 5 and 4 occur once each, 3 occurs twice, 2 three times, 1 five times, and 0 three times. The 8 leaves return five ones and three zeros, whose sum gives 5.
Python finishes the entire left subtree before starting the right subtree. This is depth-first, left-to-right evaluation. The deepest active path is fib(5), fib(4), fib(3), fib(2), fib(1): five frames, even though the whole computation makes 15 calls.
Distinguish necessary branches from repeated work
The repeated fib(3) and fib(2) nodes compute answers already obtained elsewhere. They remain separate nodes in a naive tree because the function recomputes them. For naive Fibonacci, the total call count is : 177 at 10, 21,891 at 20, and 2,692,537 at 30.
Hanoi also branches twice, but each non-base call performs a required physical move with particular peg roles. For 3 disks, its non-base levels contain 1, 2, and 4 moves, totaling 7. Reusing an earlier returned value cannot perform a later required move.
Read generated outputs at the leaves
A coin-sequence generator can add "H" first and "T" second to a prefix, stopping after three choices. Left-to-right leaves give "HHH", "HHT", "HTH", "HTT", "THH", "THT", "TTH", "TTT". Each path supplies one sequence.
Count base calls as nodes, even when they return immediately. Keep identical argument labels on separate branches unless a cache actually reuses their answers.
Key Takeaways
- Every invocation gets its own node, including repeated and base calls.
- Python completes the left recursive expression before starting the right one.
- A stack holds one active path through the recursion tree.
- Repeated arguments can reveal reusable work; branching alone does not.
- Leaf order predicts the output order of recursive generators.
2.3 Count local work, total calls, and live memory
Big-O notation describes growth as input size increases, ignoring constant factors. A recurrence separates work inside smaller calls from work done in the current call. For factorial, and : one smaller call plus constant local work, using the usual operation-count model.
Add work across a recursion tree
Draw the calls, label each node with its local work, add each level, and then add the levels. The main patterns are:
| Recurrence | How the work adds up | Time |
|---|---|---|
| About n constant-cost calls | ||
| About log₂ n constant-cost calls | ||
| Linear work per splitting level | ||
| Twice as many nodes each level |
For the quadratic pattern, the local-work sum is . For merge sort, all merges at one level together handle about n elements, and there are about splitting levels. A single halving path, as in binary search, does constant work at each level; a sorted million-element list needs at most 21 calls including a possible empty-range base call.
Include hidden copying
Python list slicing copies references into a new list. In xs[0] + sum_list(xs[1:]), the first slice copies n - 1 elements, the next n - 2, and so on. At length 1,000, that is 999 + 998 + … + 0 = 499,500 copied elements. The recurrence has linear local work and quadratic total time.
Passing the original list and an index avoids these slices. There are still about n calls, but each reads one item and advances one index, giving linear time. Counting source lines or recursive calls alone misses the difference.
Keep Hanoi moves separate from calls
With a zero base case and two calls on n - 1, levels 0 through n contain calls. Base calls do no moves. The non-base calls make moves: 15 calls and 7 moves for 3 disks, 1,023 moves for 10 disks, and about moves for 64 disks.
Naive Fibonacci also takes exponential time, but its two children have different sizes. Its call growth is roughly ; remains a valid upper bound. Do not use the full binary-tree formula as its exact call count.
Measure what remains live
| Algorithm | Time | Stack space |
|---|---|---|
| Factorial | ||
| Binary search with indexes | ||
| Naive Fibonacci | Exponential | |
| Merge sort |
Fibonacci finishes one branch before another, so exponentially many calls do not coexist. Merge sort additionally needs memory for lists. More generally, stack frames are only part of extra memory: retained slices, constructed results, and caches must also be counted.
Key Takeaways
- A recurrence counts recursive work plus all local work.
- Add the work of every node for time; use the longest active chain for stack space.
- Repeated slicing can turn linear call counts into quadratic time.
- Halving with one child gives logarithmic time; two half-size children with linear combining give n log n time.
- For Hanoi with a zero base case, calls total and moves total .
- Count allocated lists and caches in addition to stack frames.
3Process and generate sequences
Strings and lists expose a natural recursive structure: a first item followed by a smaller sequence. Nested lists add another direction, because an item can itself be a list. The same idea also builds outputs: keep or skip an element, choose the next symbol, or choose the next item in an ordering. The design must account for empty inputs, result construction, and the growing cost of producing every possible answer.
3.1 Heads, tails, and palindrome tests
For a nonempty string, the head is s[0] and the tail is s[1:]. The tail has one fewer character. Check an empty-input base case before reading the head, because ""[0] raises IndexError.
Measure or count a string
def length(s):
if s == "":
return 0
return 1 + length(s[1:])
def count_char(s, target):
if s == "":
return 0
return (1 if s[0] == target else 0) + count_char(s[1:], target)
length("recursion") returns 9. Each nonempty call contributes one; the empty call contributes zero. For count_char("mississippi", "s"), only the four matching heads contribute one. Nonmatching heads contribute zero but still pass the rest of the string onward.
Reverse while unwinding
To reverse a string, put the reversed tail before the head:
def reverse(s):
if s == "":
return s
return reverse(s[1:]) + s[0]
reverse("stack") waits to append "s" to the answer for "tack". The deepest call returns "". Unwinding builds "k", "kc", "kca", "kcat", and "kcats". Putting the head before the returned tail would rebuild the original order.
Compare both ends
A palindrome reads the same in either direction. Empty and one-character strings qualify. For a longer string, compare the ends and test the middle:
def is_palindrome(s):
if len(s) <= 1:
return True
return s[0] == s[-1] and is_palindrome(s[1:-1])
For "racecar", the calls test "racecar", "aceca", "cec", and "e". For "rocket", the first comparison fails; Python's short-circuit and skips the recursive call. An even-length palindrome such as "noon" reaches "oo" and then "". Stopping only at length 1 would miss that empty middle.
Decide which characters count before starting. To test "Never odd or even" while ignoring spaces and case, a wrapper can remove spaces and lowercase once, producing "neveroddoreven". The recursive helper then tests that prepared string consistently.
Avoid copying the remaining string
Strings are immutable. Repeatedly slicing off a character copies successively shorter strings, adding up to about copied characters. The head-and-tail versions have quadratic copying cost.
A palindrome helper can instead keep the original string:
def is_pal(s, lo, hi):
if lo >= hi:
return True
return s[lo] == s[hi] and is_pal(s, lo + 1, hi - 1)
Start with is_pal(s, 0, len(s) - 1). Each call moves both indexes inward, with constant local work, giving time. Stack depth is still linear. A recursive reversal of 5,000 characters exceeds CPython's default recursion limit; s[::-1] or a loop suits long strings.
Key Takeaways
- Check for an empty string before indexing its head.
- Reversing places the returned tail before the current head.
- A palindrome test needs empty and one-character base cases.
- Prepare spaces and case once before calling the recursive helper.
- Index parameters avoid repeated slices but still use recursive stack frames.
3.2 Build list results and follow nested structure
A flat list splits into a first element and a shorter remainder. The base answer depends on the task: an empty list sums to 0, contains no target, and produces an empty transformed list. An empty list has no largest element, so maximum-finding needs a different contract.
Choose the result-building pattern
| Task | Contribution from the head | Base answer |
|---|---|---|
| Sum | Add the head | 0 |
| Search | Return True on a match; otherwise search the tail | False |
| Select | Keep the head only if it passes a test | [] |
| Transform | Put a changed head before the transformed tail | [] |
For sum_list([4, 7, 1]), the calls leave 4, 7, and 1 waiting to be added to the base answer 0, returning 12. Selecting even values from [3, 8, 5, 6, 2] gives [8, 6, 2]. Transforming can use [f(xs[0])] + transform(xs[1:]), keeping each changed head in its original position.
For a nonempty maximum, use a one-element list as the base case. Reject [] with ValueError; otherwise return the larger of xs[0] and max_list(xs[1:]). For [3, 9, 2, 7], the returns progress from 7 to 7, then 9, then 9.
Pass an index to avoid slices
def sum_from(xs, i=0):
if i == len(xs):
return 0
return xs[i] + sum_from(xs, i + 1)
len(xs) - i counts what remains. Starting at zero visits each element once without copying the list, so time is and stack space is . The slicing form has quadratic copying cost even though its call chain has the same length.
Recurse into nested items
A nested list can contain both values and other lists. In [1, [2, [3, 4]], 5], the list nesting has three levels, and the sum of the values is 15. A loop can handle one level while recursive calls handle deeper lists.
def flatten(xs):
result = []
for item in xs:
if isinstance(item, list):
result.extend(flatten(item))
else:
result.append(item)
return result
The outer call appends 1, asks for the flattened [2, [3, 4]], and extends with [2, 3, 4]. It then appends 5, returning [1, 2, 3, 4, 5]. Empty nested lists add no elements. A nested sum uses the same branching test, adding a recursive subtotal for a list and the value itself otherwise. Folder-size calculation follows the same structure: add file sizes and recursively obtained subfolder totals.
Keep lists and their elements distinct
append(flatten(item)) adds one list object and leaves nesting in the result. extend(flatten(item)) adds its elements individually. The distinction changes the shape of the answer.
Create a fresh result for a fresh public call. A mutable default such as acc=[] is created once and reused: a doubling function can return [2, 4] for [1, 2], then [2, 4, 6] for [3]. Use None and create a list inside the function, or combine returned results as above.
Key Takeaways
- Choose the empty-input answer to match the operation; a maximum needs a nonempty input.
- An index helper gives linear list traversal without slices.
- A loop handles one list level while recursion handles nested lists.
appendadds one object;extendadds each element of an iterable.- Returning fresh results prevents state from leaking between public calls.
- A mutable default list survives beyond one call.
3.3 Generate choices one level at a time
A generating problem asks for every valid result. Each recursive level makes a choice, and each root-to-leaf path records a finished result. The base case must supply a completed empty result that larger calls can build on.
Include or exclude each element
Every subset either excludes the first element or includes it. Compute subsets of the tail once, then build both groups:
def subsets(xs):
if not xs:
return [[]]
rest = subsets(xs[1:])
return rest + [[xs[0]] + r for r in rest]
For ['a', 'b', 'c'], the output is [], ['c'], ['b'], ['b', 'c'], ['a'], ['a', 'c'], ['a', 'b'], ['a', 'b', 'c'], collected in an outer list. The first four exclude a; the next four include it.
The base result [[]] contains one subset, the empty subset. Returning [] would mean there are no subsets. Every later list comprehension would then have nothing to extend. Each distinct element doubles the number of subsets, so n distinct elements give subsets.
Choose a symbol for each position
With k choices at each of n positions and repetition allowed, there are sequences. A prefix parameter records choices already made:
def tosses(n, prefix=""):
if n == 0:
return [prefix]
return tosses(n - 1, prefix + "H") + tosses(n - 1, prefix + "T")
For three tosses, the output is "HHH", "HHT", "HTH", "HTT", "THH", "THT", "TTH", "TTT". The function finishes all sequences beginning with "H" before those beginning with "T". Its zero-position base case returns one completed prefix.
Choose the next item in an ordering
A permutation uses every item exactly once. Choose each available character as the first one, then permute the rest:
def permutations(s):
if len(s) <= 1:
return [s]
result = []
for i, char in enumerate(s):
remaining = s[:i] + s[i + 1:]
for tail in permutations(remaining):
result.append(char + tail)
return result
For "abc", this gives "abc", "acb", "bac", "bca", "cab", "cba". Distinct characters have orderings: 24 for length 4 and 3,628,800 for length 10.
Repeated symbols and growing outputs
For "aab", choosing either a as the first character starts equivalent branches. The code returns 6 strings but only 3 distinct values: "aab", "aba", and "baa". A set removes duplicate strings afterward; skipping an already-used first character at each level avoids those duplicate branches.
Output size alone imposes a time cost. All subsets of 20 distinct items require 1,048,576 result lists, while is about . Their recursion depth is only about n, but producing and storing all answers can be far more expensive. Counting answers does not include the additional cost of copying the items into them.
Key Takeaways
- Each path of choices builds one completed result.
- The empty set has one subset, so use
[[]]as the subset base result. - Subsets of n distinct items number ; length-n sequences with k repeated choices number .
- Permutations of n distinct items number .
- Repeated items can create duplicate outputs that need deduplication.
- Producing every answer costs at least as much time as the number of answers.
4Shrink problems by dividing them
Halving a problem can reduce a long chain of calls to a short one. Binary search keeps only the half that can contain the target, fast exponentiation reuses a power of half the exponent, and merge sort solves both halves before merging their results. These examples make the divide, conquer, and combine steps concrete. Their performance depends on how many smaller calls run and how much work remains outside those calls.
4.1 Search one half and reuse a half power
Divide and conquer divides a problem into smaller problems of the same kind, solves them recursively, and combines their answers. Base cases answer the smallest inputs directly. When size halves on every step, a root-to-leaf path has about levels.
Binary search keeps a range of indexes
Binary search needs a sorted list. Compare the target with the middle value. If it is smaller, discard the middle and everything to its right; if larger, discard the middle and everything to its left.
def binary_search(xs, target, lo, hi):
if lo > hi:
return -1
mid = (lo + hi) // 2
if xs[mid] == target:
return mid
if target < xs[mid]:
return binary_search(xs, target, lo, mid - 1)
return binary_search(xs, target, mid + 1, hi)
The range includes both endpoints. Start with lo=0 and hi=len(xs)-1; an empty list immediately has an empty range.
In [2, 5, 8, 12, 16, 23, 38, 56, 72, 91], searching for 23 checks index 4, whose value is 16. The next range is 5 through 9; index 7 holds 56, so the range becomes 5 through 6. Index 5 holds 23, returning 5 after three calls.
Searching for 50 checks values 16, 56, 23, and 38, then calls with lo=7, hi=6. That fifth call returns -1. Removing the checked middle with mid - 1 or mid + 1 guarantees progress. Keeping lo=mid can repeat the range 5 through 6 forever when mid is 5. The recursive branch also needs return so the found index reaches the original caller.
Sorted order justifies discarding half. On an unsorted list, the target could be in the discarded region. Passing indexes keeps the original coordinate system and avoids copying: time and stack space are . Slicing halves copies a geometric total of elements, giving copying time, and its indexes refer to the smaller lists.
Fast exponentiation halves the exponent
For non-negative integer exponents, the base is . Compute the half power once. An even exponent squares it; an odd exponent also needs one factor of x.
def power(x, n):
if n == 0:
return 1
half = power(x, n // 2)
if n % 2 == 0:
return half * half
return x * half * half
For , exponents descend through 13, 6, 3, 1, 0. Returns are 1, 3, 27, 729, and 1,594,323: five calls. For an odd exponent, n // 2 gives the exponent below the halfway point, and the extra factor restores the missing power.
Writing power(x, n // 2) * power(x, n // 2) repeats the same computation twice. The duplicated version makes 31 calls at exponent 13 and 4,095 at exponent 1024; storing half uses 5 and 12. With constant-cost arithmetic, reuse gives logarithmic time, while duplicated halves give linear time in the exponent.
Key Takeaways
- Binary search needs sorted input and an empty-range base case.
- Exclude the checked middle index from the next range.
- Index bounds preserve original positions and avoid slice copying.
- Fast power computes the half power once, squares it, and adds a factor for odd exponents.
- The number of child calls matters as much as the reduction in input size.
4.2 Sort halves, then merge their front elements
Merge sort splits a list, recursively sorts both halves, and merges the sorted results. A list with zero or one element is already sorted. Combining is essential: concatenating two sorted lists does not generally produce one sorted list.
Split until the answer is immediate
def merge_sort(xs):
if len(xs) <= 1:
return xs
mid = len(xs) // 2
left = merge_sort(xs[:mid])
right = merge_sort(xs[mid:])
return merge(left, right)
For [38, 27, 43, 3, 9, 82, 10], the halves are [38, 27, 43] and [3, 9, 82, 10]. The left half splits into [38] and [27, 43]; the latter becomes [27] and [43]. Their merge is [27, 43], then merging with [38] gives [27, 38, 43].
On the right, [3, 9] and [82, 10] become [3, 9] and [10, 82], then merge to [3, 9, 10, 82]. The final merge combines the two sorted halves.
Merge with one index per list
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
Compare the two front elements still unused. The smaller front is the smallest unused value overall because each input is sorted. Advance only the index whose value was taken. Once one side is exhausted, all remaining values on the other side can be appended in their existing order.
Merging [27, 38, 43] with [3, 9, 10, 82] chooses 3, 9, 10, 27, 38, and 43 after six comparisons, then appends 82. The result is [3, 9, 10, 27, 38, 43, 82]. Merging m total elements needs at most m - 1 front comparisons for nonempty total input.
Preserve order on ties
A stable sort keeps the original relative order of equal-key items. The condition left[i] <= right[j] takes the left item on a tie. Since splitting preserves the original order, this tie rule preserves stability through every merge. Using < instead makes a right-side equal item jump ahead.
Account for both branches and the merge
Merge sort follows : about splitting levels, each with total linear merging work. Its best, average, and worst running time are . At one million elements, is about , compared with for a quadratic work count.
The list-building version needs extra list memory and stack space. The seven-element trace has at most three splitting edges below the initial call. Both halves represent separate ranges, so merge sort does not have Fibonacci's overlapping-subproblem pattern.
Stopping only on length zero leaves a one-element list recurring on itself. Stopping a merge when one side runs out without copying the other loses values. Returning left + right skips the comparisons that establish order across the halves.
Key Takeaways
- Lists of length zero or one are the merge-sort base cases.
- Merge compares the two unused fronts and advances only the chosen side.
- Append every leftover value after one input runs out.
- Take from the left on ties to keep the sort stable.
- Two half-size sorts plus linear merging give time.
- This version needs linear extra list memory and logarithmic stack space.
5Choose loops, stacks, and cached recursion
The shape of a problem helps determine whether recursion makes its solution easier to read. Python’s execution costs also matter: a long call chain consumes stack space even when every call is correct. Loops and explicit stacks can perform the same computation, while memoization attacks a different cost by reusing answers. Comparing these choices requires checking both the work that repeats and the state that remains in memory.
5.1 Convert recursion to iteration without losing state
Recursion and iteration have the same computing power. A loop can reproduce a recursive computation, using an explicit stack when necessary. A loop can also be expressed recursively. The useful choice depends on how clearly the code expresses the problem and what memory its execution needs.
Move a simple chain into a loop
For factorial, the base answer becomes the initial result. The recursive combination becomes a repeated update:
def factorial_loop(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
For a non-negative integer input of 5, the updates produce 2, 6, 24, and 120. Both versions do linear arithmetic work, but the recursive version keeps linear stack space and the loop keeps a constant number of variables.
Recognize a tail call
A tail call is the last action: the caller returns the inner answer unchanged. return n * factorial(n - 1) is not a tail call, because multiplication waits until the smaller call returns. An accumulator carries the completed work forward:
def fact_acc(n, acc=1):
if n == 0:
return acc
return fact_acc(n - 1, acc * n)
fact_acc(5) visits argument pairs (5, 1), (4, 5), (3, 20), (2, 60), (1, 120), (0, 120). The base returns the finished answer. A direct loop version is:
def fact_acc_loop(n, acc=1):
while n != 0:
acc *= n
n -= 1
return acc
Some language implementations eliminate tail calls by reusing a frame. CPython does not eliminate Python tail calls, and the Java virtual machine does not provide this optimization either. The tail-recursive Python form still creates a frame per call.
Replace branching calls with an explicit stack
For nested data, a stack can hold items awaiting processing:
def flatten_loop(xs):
stack = [xs]
result = []
while stack:
item = stack.pop()
if isinstance(item, list):
stack.extend(reversed(item))
else:
result.append(item)
return result
The last item pushed is the first popped. Pushing each list in reverse makes the leftmost element the next one processed. For [1, [2, [3, 4]], 5], the result is [1, 2, 3, 4, 5]. Pushing in the original order visits 5, 4, 3, 2, 1 instead. A sum would still be 15 and hide the order change; flattening exposes it. The explicit stack uses memory for pending work even though it avoids recursive frames.
Match the approach to the work
| Situation | Useful choice | Reason |
|---|---|---|
| Nested lists or repeated splitting | Recursion | Code follows the structure |
| A long flat sequence | Loop | Constant auxiliary state and no deep call chain |
| Branching work needing controlled order | Explicit stack | Pending items and visit order are visible |
A 100,000-element linear recursive traversal exceeds Python's usual recursion limit. A loop also avoids per-call overhead. A direct recursive-to-loop conversion can keep the same Big-O time bound.
An iterative Fibonacci function starts with a, b = 0, 1 and repeats a, b = b, a + b exactly n times, then returns a. It computes each next number once in arithmetic steps, avoiding naive recursion's repeated subproblems.
Key Takeaways
- A direct loop conversion can preserve time complexity while reducing stack space.
- A tail call returns its result unchanged, with no work left afterward.
- An accumulator carries work already completed.
- CPython keeps recursive frames even for tail calls.
- An explicit stack can replace branching recursion; reverse pushes to preserve left-to-right order.
- Iterative Fibonacci avoids recomputing earlier values.
5.2 Reuse answers with memoization
Memoization stores a completed result under the arguments that produced it. A later call with the same arguments reads the stored answer. It is useful when different branches ask for the same subproblem, as naive Fibonacci does.
Look up before computing, store before returning
memo = {}
def fib(n):
if n in memo:
return memo[n]
result = n if n < 2 else fib(n - 1) + fib(n - 2)
memo[n] = result
return result
With an empty table, fib(5) makes 9 calls instead of 15. It computes each result for arguments 0 through 5 once. A later request for an existing argument still calls the function, but returns at the lookup without expanding children.
For fib(30), a fresh manual table gives 59 calls and 31 stored results, compared with 2,692,537 calls without caching. Constant-cost arithmetic analysis drops from exponential time to time, using cache entries. Memoization trades memory for less repeated computation.
Use Python's caching decorators
from functools import cache
@cache
def fib_cached(n):
if n < 2:
return n
return fib_cached(n - 1) + fib_cached(n - 2)
cache is available from Python 3.9 and keeps all results. After one fresh call of fib_cached(30), cache_info() reports 31 misses and 28 hits: misses execute the body, while hits reuse answers. These sum to 59 requests to the cached function.
@lru_cache(maxsize=128) retains at most 128 entries and evicts the least recently used; maxsize=None removes that bound. Decorator arguments must be hashable. A tuple of hashable items can serve where a list cannot.
Include every part of the subproblem in the key
Binomial coefficients count ways to choose k items from n. For , the boundary cases are ; other cases use .
A manual cache uses (n, k) as its key. Using only n confuses different tasks: and . Naive makes 19 calls. At , naive recursion makes 369,511 calls; a fresh manual cache makes 201 calls and stores 120 results.
Check when reusing an answer is valid
A pure function depends only on its arguments and has no side effects. Cache this kind of computation. A function that prints a message or reads the clock has behavior a stored answer cannot repeat correctly: a cache hit skips execution of the body.
Caching does not remove useful work from one factorial chain or an index-based binary search, whose arguments do not repeat. Merge sort solves independent input ranges, so it also lacks the overlapping structure that makes caching Fibonacci useful.
Repeated work and depth are different problems
The first memoized Fibonacci call still descends through decreasing arguments before storing answers on the return path. A fresh fib(5000) therefore exceeds the default recursion limit. Previously cached lower values can shorten later chains, but calling in batches must still respect the actual available depth. A loop avoids the recursive chain altogether.
Key Takeaways
- Memoization reuses a completed result when the same arguments recur.
- Check the cache first and store each newly computed answer.
- Cache keys must identify the complete subproblem.
- Python cache decorators need hashable arguments;
cacheis unbounded. - Cache pure computations so skipping the body preserves behavior.
- Memoization removes repeated work, but the first call can still have linear recursion depth.
- Count cache storage as part of extra memory.
Recursion examples
1Build and check a recursive function
12 steps
- 1IntroductionOne call solves one smaller task
A recursive function needs an answer it can give directly and a way to build larger answers from smaller ones. Start with a simple sum, then design a digit-sum function. The same design questions will also produce a plan for moving a stack of disks.
- 2ExplanationGive zero a direct answer
For a non-negative integer
n, letsum_to(n)return the sum from 1 throughn. At zero, there are no values to add, so the answer is 0.For a positive input, separate the last value from the rest:
return n + sum_to(n - 1). The smaller call returns the sum throughn - 1; addingnsupplies the one missing value. The zero case makes no recursive call. - 3ExampleFollow one sum down and back
For
sum_to(3), the calls use arguments 3, 2, 1, and 0. Each positive call waits to add its own argument to a smaller answer.The base call returns 0. Then the call on 1 returns 1, the call on 2 returns 3, and the call on 3 returns 6. The original caller receives the final value through the chain of
returnstatements. - 4ChallengeFind the unreachable base case
A function stops when
n == 0and otherwise returnsn + total(n - 2). What happens for input 5?---reveal---
The arguments are 5, 3, 1, -1, -3, and so on. Zero is never reached, so Python eventually raises
RecursionError. The decrease must reach a stopping input for every valid starting value; getting numerically smaller alone does not ensure that. - 5TipReturn the smaller answer
A call such as
sum_to(n - 1)computes a value, but placing it on a line by itself throws that value away. Falling off the end of a Python function returnsNone.The caller needs
return n + sum_to(n - 1)so it can receive the completed sum. Printing the inner result only displays it; it does not provide a return value for the waiting addition. - 6ConnectionTwo functions can share one descent
An evenness test can call an oddness test on
n - 1, and the oddness test can call the evenness test onn - 1. At zero, evenness returnsTrueand oddness returnsFalse.This is mutual recursion. The function name changes along the chain, but the non-negative argument still approaches zero. The same progress check applies to a cycle of functions as to a direct self-call.
- 7ExplanationDesign a digit sum at one level
For a non-negative integer, take the number of digits as the size. A single-digit number already is its digit sum.
For a longer number,
n % 10gives its last digit andn // 10gives the remaining digits. Assuming the smaller call returns their digit sum, the current answer isn % 10 + sum_digits(n // 10). This is the recursive leap of faith: use the smaller answer to design one correct step. - 8ExampleRemove digits, then add them
For
sum_digits(582), split the work into2 + sum_digits(58). The next call needs8 + sum_digits(5).The single-digit base case returns 5. Unwinding first gives 8 + 5 = 13, then 2 + 13 = 15. The size decreases from three digits to two to one, and every smaller call performs the same digit-sum task.
- 9ChallengeChoose a base case for powers
A power function for non-negative integer exponents stops at
n == 1and otherwise returnsx * power(x, n - 1). What valid input does it miss, and how should it stop there?---reveal---
It misses exponent zero. Return 1 when
n == 0, because any base to the zero power is 1 in this algorithm. Subtracting from zero would move into negative exponents and never reach 1. - 10ExampleMove a stack with two smaller moves
To move three Hanoi disks from A to C, first move the top two from A to B, using C as the spare. Then move the largest disk from A to C. Finally move the two-disk stack from B to C, using A as the spare.
A two-disk transfer needs three moves, so the full plan needs 3 + 1 + 3 = 7. The zero-disk base case performs no move. Each recursive call must receive the peg roles for its own transfer.
- 11ChallengeCheck a design and its return value
A non-negative digit-sum function returns 0 for
n < 10; otherwise it returnsn % 10 + digits(n // 10). It stops for input 734. Does it return the correct digit sum?---reveal---
No. It returns 4 + 3 + 0 = 7, losing the leading digit 7. The size measure guarantees termination, but the base answer must also be correct. Returning
nfor the single-digit base case produces 14. - 12RecapKeep the three checks separate
Check the base answer, the way smaller answers are combined, and progress toward a stopping input. Each can fail independently. Helper parameters can carry the extra state a smaller task needs, such as a position or the peg roles in Hanoi.
2Trace calls and account for their work
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionExecution has a path and a whole tree
- 2ExplanationKeep a frame for each call
- 3ExampleRecord the pending operation
- 4ChallengePredict work after the call
- 5TipA valid chain can still be too deep
- 6ExplanationGive every invocation a node
- 7ExampleFinish the left subtree first
- 8ChallengeCount a repeated subproblem
- 9ExplanationWrite local work beside the calls
- 10ExampleSee why slicing changes the total
- 11ExampleAdd work across a split tree
- 12ChallengeSeparate Hanoi moves from base calls
- 13Key InsightCount memory that is live together
- 14ChallengeDiagnose a misleading cost claim
- 15RecapUse the right count for the question
3Process a sequence and build every choice
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionShorter sequences lead to direct answers
- 2ExplanationCount one head, then the tail
- 3ExampleBuild a reversal on the way back
- 4ExampleLet matching ends expose the middle
- 5ChallengeRepair the even-length stopping case
- 6ConnectionMake the base answer match the task
- 7ExplanationAdvance an index without making a copy
- 8ExampleFlatten a nested list in order
- 9ChallengeChoose append or extend
- 10ExplanationStart subsets with one empty answer
- 11ExampleBuild four subsets from two
- 12ExplanationLet each leaf finish a sequence
- 13ExampleChoose each next character once
- 14ChallengeRecognize duplicate permutation branches
- 15ChallengeCompare traversal with generation
- 16RecapCheck the shape of the returned answer
4Search, raise powers, and merge sorted halves
17 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionAsk how many smaller answers are needed
- 2ExplanationKeep inclusive search bounds
- 3ExampleTrace a successful search
- 4ExampleTrace a missing target to an empty range
- 5ChallengeCheck the range that repeats
- 6ExplanationCompute the half power once
- 7ExampleUnwind an odd power
- 8Key InsightHalving alone does not guarantee logarithmic work
- 9ExplanationSplit before sorting
- 10ExampleTake the smallest unused front
- 11ExampleFinish the merge without losing leftovers
- 12ExplanationKeep equal-key records in order
- 13ChallengeCatch a combine-step error
- 14ConnectionAdd all merges at one level
- 15ChallengeChoose the right implementation repair
- 16ChallengeCombine the cost and correctness checks
- 17RecapCount branches and the combine step
5Choose a loop or cache the repeated work
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionDeep calls and repeated work need different fixes
- 2ExampleTurn the base answer into the starting state
- 3ExplanationMove pending work into an accumulator
- 4ChallengeCheck what Python actually optimizes
- 5ExampleMake an explicit stack preserve order
- 6ExplanationFind the argument that appears again
- 7ExampleTrace lookup, compute, and store
- 8ChallengeUse a complete cache key
- 9TipChoose a cache bound and valid arguments
- 10Key InsightA cache hit skips the function body
- 11ChallengeExplain why the first chain stays deep
- 12ChallengeChoose an approach for a long sequence
- 13RecapMatch the repair to the actual cost
Recursion practice questions
Set 1: Trace, process, search, and reuse answers10 Practice Questions
Question 1 of 10
mid = (lo + hi) // 2. Search [1, 7, 13, 21, 29, 36, 48, 59] for 48. What middle indexes are checked?Show answerHide answer
Question 2 of 10
n == 0 and otherwise calls itself on n + 1. Starting with a positive integer, why does it fail to finish?Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
"" for empty input and otherwise returns s[0] + reverse(s[1:]). What does it return for "lamp"?Show answerHide answer
"lamp". To reverse, the returned tail must come before the head. The recursion reaches its base case correctly; the error is in the order used to combine characters during unwinding.Question 5 of 10
result = 1 and multiplies by each i in range(2, n). It is meant to replace factorial for positive n. What does it return at 6, and what bound repairs it?Show answerHide answer
n + 1, giving 720. Changing only the starting value to 1 does not repair the missing final factor because multiplication by 1 leaves the result unchanged.Question 6 of 10
What does show(2) print, in order?
def show(n):
if n == 0:
return
print(n)
show(n - 1)
print(-n)
Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
[2, 7, 11] with [4, 8] by comparing unused fronts. How many front comparisons occur before a list runs out?Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
@cache, returns n below 2, and evaluates fib(n - 1) before fib(n - 2). After clearing its cache, it calls fib(7) and then fib(8). What totals does cache_info() report?Show answerHide answer
Set 2: Recursion essentials and a debugging challenge10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
n * product(n - 1) for positive n. What should it return at zero to compute factorials correctly?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
n - 1 until a base case at zero. Including the initial and base calls, what is its maximum number of active recursive frames?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
"coconut" and target "o"?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
return helper(n - 1, acc + n) with no other work afterward. What kind of call is this?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
f(n) = 3 + f(n - 1) with f(0) = 2, what values return from the calls on 1, 2, and 3, in that order?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
[]. What collection does it return for ["x", "y"]?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
This sorter is called on [5]. What happens? After changing only the base test to len(xs) <= 1, what does it return for [4, 1, 3, 2], and what further change is needed?
def sort(xs):
if len(xs) == 0:
return xs
mid = len(xs) // 2
left = sort(xs[:mid])
right = sort(xs[mid:])
return left + right
Show answerHide answer
Save this lesson to see this answer.
Set 3: Connect implementation choices with cost10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
n < 10. What recursive expression correctly handles the other inputs?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
This helper should test any string, starting with lo=0 and hi=len(s)-1. What two repairs are needed, and what should it return for "abca"?
def pal(s, lo, hi):
if lo == hi:
return True
return s[lo] == s[hi] or pal(s, lo + 1, hi - 1)
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
n // 2 and stops at zero. Including the initial and base calls, how many calls compute power(5, 18)?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
[3, [1, 8], 6]?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
n below 2 and otherwise calls on n - 1 and n - 2. How many calls to fib(1) occur while computing fib(4)?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
[9, [], [4, [6]], 1] from left to right?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
(4, "L") and the right half contains (4, "R"), originally in that order. Which record should be taken first, and why?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 4: Debug recursive and iterative solutions10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
a when b == 0 and otherwise calls gcd(b, a % b). What quantity guarantees progress when b > 0?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
xs[1:] until the list is empty. For an original length of 8, how many element references are copied into slices altogether?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
acc=[] and appends plain values into it. After a fresh definition, flatten([2, [5]]) returns [2, 5]. What does a later flatten([7]) return, and what change prevents the problem?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
(text, target) as its key but advances through the text with an additional index i. It stores every call’s result. After computing the full count, a call at a later position returns the full count again. What repair preserves reusable answers?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
What value does f(4) return?
def f(n):
if n <= 1:
return 2
smaller = f(n - 2)
return smaller + n
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
"mmn" without deduplication. How many output entries and distinct strings does it produce?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
[2, [9, [], 4], 7]. It uses a LIFO stack and currently pushes list items in their original order. What push rule and output give an equivalent traversal to recursion?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
n - 1, stops at zero, and keeps only constant-size local state. What are the exact call count and stack depth for input 4?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
n distinct labels, copies each chosen label into its output list, and retains all lists. What lower bounds apply to time and output storage as n grows?Show answerHide answer
Save this lesson to see this answer.
Set 5: Combine design, analysis, and reuse10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
What does f(3) return?
def f(n):
if n == 0:
return 0
f(n - 1)
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
"A", "B", and "C", in that order, at every position. It finishes each branch before starting the next. What are its fourth and fifth outputs?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
"Step on no pets". What change fixes the intended phrase test without adding work at every recursive level?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
[3, 8, 14, 20, 27] seeks 25 with inclusive bounds and floor midpoints. A version uses lo=mid on the right branch and hi=mid - 1 on the left. What repeated range causes failure?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
For input 826, what does this digit-sum function return, and which changes repair it for every non-negative integer?
def digits(n):
if n < 10:
return 0
return n % 10 + digits(n % 10)
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
[1, 6] with [2, 3, 8]. Immediately after the left list runs out, what is the result so far and what remains to append?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Accumulator
Append
[2, 6] to [5] produces [5, [2, 6]], which keeps an extra nesting level.Auxiliary space
B
Base case
Binary recursion
Binary search
C
Cache hit
Cache key
Cache miss
Call stack
D
Divide and conquer
E
Empty search range
lo > hi after a comparison.Explicit stack
Exponential growth
Extend
[5] with [2, 6] produces [5, 2, 6], adding two values instead of one list.F
Fast exponentiation
Flattening
[8, [3, 1]] from left to right returns [8, 3, 1] without the inner list.H
Hashable argument
Head
Helper function
I
Iteration
L
Leaf call
Least recently used cache
lru_cache may recompute an old result after more recent entries displace it.Leftover elements
Linear recursion
Local work
M
Memoization
Merge
[1, 9] and [4, 6] takes 1, 4, and 6 before appending the leftover 9.Merge sort
[7, 2, 5, 1] merges the smaller answers [2, 7] and [1, 5].Multiple recursion
Mutable default argument
Mutual recursion
N
Nested list
[4, [2, [7]]], a nested-list sum recurses into each inner list to reach every number.O
Output-size lower bound
P
Palindrome
"level" reduces to "eve" and then to the one-character string "v".Permutation
Prefix
"HT" with another symbol before reaching a leaf.Progress toward a base case
Pure function
R
Recurrence
Recursion
Recursion depth
Recursion tree
RecursionError
RecursionError even with a correct base case.Recursive case
Recursive leap of faith
Root call
fib(6), the root call has children with arguments 5 and 4.S
Size measure
Stable sort
Stack frame
n.Stack overflow
Stack space
Subset
T
Tail
"river", the tail is "iver", and Python slicing creates a new string for it.Tail call
Time complexity
Towers of Hanoi
U
Unwinding
W
Winding
Wrapper function
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.