Recursion

Learn to solve problems by having a function call itself on smaller inputs. Write correct base and recursive cases, trace calls on the call stack and in recursion trees, and process strings, lists and nested lists recursively. Use divide and conquer for binary search, fast exponentiation and merge sort, estimate the time and memory recursive algorithms need, decide when a loop is the better choice, and remove repeated work with memoization. All examples are in Python.

IntermediateLesson 2 of 10 in Data Structures and Algorithms Course

What you will learn

  1. 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 case
      Explain 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 step
      Turn 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.
  2. 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 stack
      Follow 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 calls
      Represent 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 algorithms
      Write 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.
  3. 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 recursively
      Split 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 recursively
      Write recursive functions that sum, search, filter and transform lists, and use recursion to handle lists nested to any depth.
    • Generate all subsets, sequences and permutations
      Use 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.
  4. 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 powers
      Recognize 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 sort
      Trace 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.
  5. 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 them
      Rewrite 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 memoization
      Cache 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.

Recursion study guide

5 chapters

1

Build 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: 0!=1 and n!=n⋅(n−1)! 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: F(n)=F(n−1)+F(n−2). Its base cases are F(0)=0 and F(1)=1. 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
  1. Choose a size measure.
  2. Give the smallest valid inputs direct answers.
  3. Assume the function solves smaller inputs correctly.
  4. Combine those smaller answers into the current answer.
  5. 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:

  1. Move the top n - 1 disks to the spare peg.
  2. Move the largest disk from source to target.
  3. 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 2n−1.

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.
2

Follow 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.

CallWork waitingReturn value
factorial(4)4 times the inner answer24
factorial(3)3 times the inner answer6
factorial(2)2 times the inner answer2
factorial(1)1 times the inner answer1
factorial(0)No multiplication1

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 n+1, 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
PatternCalls made by a recursive caseExamples
Linear recursionOneFactorial, summation, binary search
Binary recursionTwoFibonacci, merge sort, Hanoi
Multiple recursionMore than twoPermutations 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 2F(n+1)−1: 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, T(n)=T(n−1)+c and T(0)=c: 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:

RecurrenceHow the work adds upTime
T(n)=T(n−1)+cAbout n constant-cost callsO(n)
T(n)=T(n−1)+cnn+(n−1)+⋯+1O(n2)
T(n)=T(n/2)+cAbout log₂ n constant-cost callsO(log⁡n)
T(n)=2T(n/2)+cnLinear work per splitting levelO(nlog⁡n)
T(n)=2T(n−1)+cTwice as many nodes each levelO(2n)

For the quadratic pattern, the local-work sum is n(n+1)/2. For merge sort, all merges at one level together handle about n elements, and there are about log⁡2n 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 1+2+⋯+2n=2n+1−1 calls. Base calls do no moves. The non-base calls make 2n−1 moves: 15 calls and 7 moves for 3 disks, 1,023 moves for 10 disks, and about 1.8×1019 moves for 64 disks.

Naive Fibonacci also takes exponential time, but its two children have different sizes. Its call growth is roughly 1.618n; O(2n) remains a valid upper bound. Do not use the full binary-tree formula as its exact call count.

Measure what remains live
AlgorithmTimeStack space
FactorialO(n)O(n)
Binary search with indexesO(log⁡n)O(log⁡n)
Naive FibonacciExponentialO(n)
Merge sortO(nlog⁡n)O(log⁡n)

Fibonacci finishes one branch before another, so exponentially many calls do not coexist. Merge sort additionally needs O(n) 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 2n+1−1 and moves total 2n−1.
  • Count allocated lists and caches in addition to stack frames.
3

Process 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 n2/2 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 O(n) 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
TaskContribution from the headBase answer
SumAdd the head0
SearchReturn True on a match; otherwise search the tailFalse
SelectKeep the head only if it passes a test[]
TransformPut 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 O(n) and stack space is O(n). 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.
  • append adds one object; extend adds 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 2n subsets.

Choose a symbol for each position

With k choices at each of n positions and repetition allowed, there are kn 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 n! 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 20! is about 2.4×1018. 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 2n; length-n sequences with k repeated choices number kn.
  • Permutations of n distinct items number n!.
  • Repeated items can create duplicate outputs that need deduplication.
  • Producing every answer costs at least as much time as the number of answers.
4

Shrink 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 log⁡2n 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 O(log⁡n). Slicing halves copies a geometric total of elements, giving O(n) copying time, and its indexes refer to the smaller lists.

Fast exponentiation halves the exponent

For non-negative integer exponents, the base is x0=1. 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 313, 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 T(n)=2T(n/2)+cn: about log⁡2n splitting levels, each with total linear merging work. Its best, average, and worst running time are O(nlog⁡n). At one million elements, nlog⁡2n is about 2×107, compared with 1012 for a quadratic work count.

The list-building version needs O(n) extra list memory and O(log⁡n) 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 O(nlog⁡n) time.
  • This version needs linear extra list memory and logarithmic stack space.
5

Choose 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
SituationUseful choiceReason
Nested lists or repeated splittingRecursionCode follows the structure
A long flat sequenceLoopConstant auxiliary state and no deep call chain
Branching work needing controlled orderExplicit stackPending 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 O(n) 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 O(n) time, using O(n) 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 0≤k≤n, the boundary cases are C(n,0)=C(n,n)=1; other cases use C(n,k)=C(n−1,k−1)+C(n−1,k).

A manual cache uses (n, k) as its key. Using only n confuses different tasks: C(5,1)=5 and C(5,2)=10. Naive C(5,2) makes 19 calls. At C(20,10)=184,756, 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; cache is 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

5 Walkthroughs

1

Build and check a recursive function

12 steps
Design stopping cases and smaller calls, then apply the design to digit sums and Towers of Hanoi.
  1. 1
    IntroductionOne 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.

  2. 2
    ExplanationGive zero a direct answer

    For a non-negative integer n, let sum_to(n) return the sum from 1 through n. 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 through n - 1; adding n supplies the one missing value. The zero case makes no recursive call.

  3. 3
    ExampleFollow 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 return statements.

  4. 4
    ChallengeFind the unreachable base case

    A function stops when n == 0 and otherwise returns n + 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.

  5. 5
    TipReturn 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 returns None.

    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.

  6. 6
    ConnectionTwo 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 on n - 1. At zero, evenness returns True and oddness returns False.

    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.

  7. 7
    ExplanationDesign 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 % 10 gives its last digit and n // 10 gives the remaining digits. Assuming the smaller call returns their digit sum, the current answer is n % 10 + sum_digits(n // 10). This is the recursive leap of faith: use the smaller answer to design one correct step.

  8. 8
    ExampleRemove digits, then add them

    For sum_digits(582), split the work into 2 + sum_digits(58). The next call needs 8 + 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.

  9. 9
    ChallengeChoose a base case for powers

    A power function for non-negative integer exponents stops at n == 1 and otherwise returns x * 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.

  10. 10
    ExampleMove 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.

  11. 11
    ChallengeCheck a design and its return value

    A non-negative digit-sum function returns 0 for n < 10; otherwise it returns n % 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 n for the single-digit base case produces 14.

  12. 12
    RecapKeep 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.

2

Trace calls and account for their work

15 steps
Follow waiting operations, draw a branching tree, and separate running time from stack and allocated memory.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionExecution has a path and a whole tree
  2. 2
    ExplanationKeep a frame for each call
  3. 3
    ExampleRecord the pending operation
  4. 4
    ChallengePredict work after the call
  5. 5
    TipA valid chain can still be too deep
  6. 6
    ExplanationGive every invocation a node
  7. 7
    ExampleFinish the left subtree first
  8. 8
    ChallengeCount a repeated subproblem
  9. 9
    ExplanationWrite local work beside the calls
  10. 10
    ExampleSee why slicing changes the total
  11. 11
    ExampleAdd work across a split tree
  12. 12
    ChallengeSeparate Hanoi moves from base calls
  13. 13
    Key InsightCount memory that is live together
  14. 14
    ChallengeDiagnose a misleading cost claim
  15. 15
    RecapUse the right count for the question
3

Process a sequence and build every choice

16 steps
Work through string tests, nested-list flattening, and recursive generation of subsets and permutations.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionShorter sequences lead to direct answers
  2. 2
    ExplanationCount one head, then the tail
  3. 3
    ExampleBuild a reversal on the way back
  4. 4
    ExampleLet matching ends expose the middle
  5. 5
    ChallengeRepair the even-length stopping case
  6. 6
    ConnectionMake the base answer match the task
  7. 7
    ExplanationAdvance an index without making a copy
  8. 8
    ExampleFlatten a nested list in order
  9. 9
    ChallengeChoose append or extend
  10. 10
    ExplanationStart subsets with one empty answer
  11. 11
    ExampleBuild four subsets from two
  12. 12
    ExplanationLet each leaf finish a sequence
  13. 13
    ExampleChoose each next character once
  14. 14
    ChallengeRecognize duplicate permutation branches
  15. 15
    ChallengeCompare traversal with generation
  16. 16
    RecapCheck the shape of the returned answer
4

Search, raise powers, and merge sorted halves

17 steps
Trace divide and conquer through index ranges, reused half powers, and a complete merge.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionAsk how many smaller answers are needed
  2. 2
    ExplanationKeep inclusive search bounds
  3. 3
    ExampleTrace a successful search
  4. 4
    ExampleTrace a missing target to an empty range
  5. 5
    ChallengeCheck the range that repeats
  6. 6
    ExplanationCompute the half power once
  7. 7
    ExampleUnwind an odd power
  8. 8
    Key InsightHalving alone does not guarantee logarithmic work
  9. 9
    ExplanationSplit before sorting
  10. 10
    ExampleTake the smallest unused front
  11. 11
    ExampleFinish the merge without losing leftovers
  12. 12
    ExplanationKeep equal-key records in order
  13. 13
    ChallengeCatch a combine-step error
  14. 14
    ConnectionAdd all merges at one level
  15. 15
    ChallengeChoose the right implementation repair
  16. 16
    ChallengeCombine the cost and correctness checks
  17. 17
    RecapCount branches and the combine step
5

Choose a loop or cache the repeated work

13 steps
Convert a recursive chain, preserve order with an explicit stack, and decide when caching is useful and valid.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionDeep calls and repeated work need different fixes
  2. 2
    ExampleTurn the base answer into the starting state
  3. 3
    ExplanationMove pending work into an accumulator
  4. 4
    ChallengeCheck what Python actually optimizes
  5. 5
    ExampleMake an explicit stack preserve order
  6. 6
    ExplanationFind the argument that appears again
  7. 7
    ExampleTrace lookup, compute, and store
  8. 8
    ChallengeUse a complete cache key
  9. 9
    TipChoose a cache bound and valid arguments
  10. 10
    Key InsightA cache hit skips the function body
  11. 11
    ChallengeExplain why the first chain stays deep
  12. 12
    ChallengeChoose an approach for a long sequence
  13. 13
    RecapMatch the repair to the actual cost

Recursion practice questions

50 Practice Questions in 5 sets

Set 1: Trace, process, search, and reuse answers10 Practice Questions

Question 1 of 10

Binary search uses inclusive bounds and mid = (lo + hi) // 2. Search [1, 7, 13, 21, 29, 36, 48, 59] for 48. What middle indexes are checked?
  1. 4, 6
  2. 3, 6
  3. 3, 5, 6
  4. 3, 5, 7, 6
Show answerHide answer
Answer: C
The initial middle index is 3, holding 21, so the range becomes 4 through 7. Its middle is 5, holding 36, so the range becomes 6 through 7 and checks index 6. Jumping from 3 directly to 6 uses a different midpoint rule and skips the actual second comparison.

Question 2 of 10

A function stops at n == 0 and otherwise calls itself on n + 1. Starting with a positive integer, why does it fail to finish?
  1. Its base case runs before the call.
  2. Its argument moves away from zero.
  3. Each call changes the caller’s value.
  4. Its base answer returns too soon.
Show answerHide answer
Answer: B
Starting from a positive value, adding 1 produces only larger positive arguments, so the zero base case is unreachable. The presence of a stopping test is insufficient when no call reaches it. Recursive calls create new local argument bindings; they do not change the earlier caller’s value.

Question 3 of 10

A recursion tree has one root call and two base-case child calls. How many calls does the complete computation make?
  1. 1
  2. 2
  3. 4
  4. 3
Show answerHide answer
Answer: D
The root and both children are invocations, giving three calls in total. Counting only the two children omits the initial call. Immediate base-case returns still belong to the execution tree even though they have no child calls and may do very little local work.

Question 4 of 10

A reverse function returns "" for empty input and otherwise returns s[0] + reverse(s[1:]). What does it return for "lamp"?
  1. "lamp"
  2. "pmal"
  3. "lmap"
  4. "malp"
Show answerHide answer
Answer: A
The function places every head before its processed tail, so it reconstructs the original string "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

A loop starts with 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?
  1. 720; use range(2, n + 1).
  2. 120; use range(1, n).
  3. 120; use range(2, n + 1).
  4. 24; use range(1, n + 1).
Show answerHide answer
Answer: C
Python excludes the range endpoint, so the loop multiplies 2 through 5 and returns 120. Including 6 requires the endpoint 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)
  1. 2, 1, -1, -2
  2. 2, 1, -2, -1
  3. 1, 2, -2, -1
  4. 2, -2, 1, -1
Show answerHide answer
Answer: A
Positive values print before each smaller call, giving 2 then 1. After the base case returns, the frame on 1 prints -1 before the frame on 2 prints -2. Keeping the positive order for the negative values misses that the most recent waiting frame resumes first.

Question 7 of 10

A recursive maximum function handles nonempty numeric lists. It returns the only element at length 1. What should the recursive case return?
  1. max(xs[0], len(xs[1:]))
  2. xs[0] + max_list(xs[1:])
  3. max_list(xs[1:])
  4. max(xs[0], max_list(xs[1:]))
Show answerHide answer
Answer: D
The largest value is either the head or the largest value in the tail, so comparing those two answers covers the whole list. Returning just the tail maximum loses a largest value at the first position. Adding the two values computes a different quantity instead of selecting an existing maximum.

Question 8 of 10

Merge [2, 7, 11] with [4, 8] by comparing unused fronts. How many front comparisons occur before a list runs out?
  1. 2
  2. 4
  3. 3
  4. 5
Show answerHide answer
Answer: B
The comparisons choose 2, then 4, then 7, then 8. The right list is now exhausted, so 11 is appended without another front comparison. Counting five treats the leftover append as a comparison, but no second front value remains to compare it against.

Question 9 of 10

How many subsets does a set of five distinct items have?
  1. 10
  2. 25
  3. 32
  4. 120
Show answerHide answer
Answer: C
Each of five items has two independent possibilities: included or excluded, giving 2 to the fifth power, or 32 subsets. The factorial value 120 counts orderings of all five distinct items. Subsets make membership choices and include the empty subset; they do not arrange every item in order.

Question 10 of 10

A Fibonacci function uses @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?
  1. 7 hits and 9 misses
  2. 5 hits and 9 misses
  3. 7 hits and 8 misses
  4. 6 hits and 10 misses
Show answerHide answer
Answer: A
The first call computes arguments 0 through 7: eight misses and five hits. The new call on 8 adds one miss, then hits the cached values for 7 and 6, giving seven hits and nine misses overall. Counting only one new hit misses that both of the new root’s children are already cached.
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

A product function for non-negative integers returns n * product(n - 1) for positive n. What should it return at zero to compute factorials correctly?
  1. 0
  2. n - 1
  3. 1
  4. None
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A recursive function on input 6 calls itself on n - 1 until a base case at zero. Including the initial and base calls, what is its maximum number of active recursive frames?
  1. 7
  2. 5
  3. 6
  4. 8
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A string counter returns 0 for an empty string and adds 1 for each head equal to the target. What does it return for the string "coconut" and target "o"?
  1. 1
  2. 3
  3. 7
  4. 2
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Binary search is given an unsorted list. Why is discarding one half after a middle comparison unsafe?
  1. The middle index cannot be calculated.
  2. The target can lie in the discarded half.
  3. The list needs a one-element base case.
  4. The comparison must visit both ends first.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A recursive function executes return helper(n - 1, acc + n) with no other work afterward. What kind of call is this?
  1. A base call
  2. A tail call
  3. A cached call
  4. A branching call
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

For f(n) = 3 + f(n - 1) with f(0) = 2, what values return from the calls on 1, 2, and 3, in that order?
  1. 3, 6, 9
  2. 11, 8, 5
  3. 2, 5, 8
  4. 5, 8, 11
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What value should a recursive list-product function return for an empty list so that it can multiply the remaining elements correctly?
  1. 1
  2. 0
  3. -1
  4. None
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A cached function prints a message, then returns the square of its argument. After clearing the cache, it is called twice with 7. How many messages print, and why?
  1. Two messages; every request executes the body.
  2. One message; the second square is not returned.
  3. One message; the second request skips the body.
  4. Two messages; the second request clears the cache.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A subset generator computes tail subsets and extends each by the head, but its empty-input base returns []. What collection does it return for ["x", "y"]?
  1. []
  2. [[]]
  3. [["x"], ["y"]]
  4. [[], ["x"], ["y"], ["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
  1. Repeats the singleton; returns [1, 4, 2, 3]; replace joining with merging.
  2. Returns [5]; returns [4, 1, 3, 2]; replace joining with merging.
  3. Repeats the singleton; returns [1, 2, 3, 4]; keep joining the halves.
  4. Repeats the singleton; returns [4, 1, 3, 2]; replace joining with merging.
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

A digit-count function handles non-negative integers, with zero counted as one digit. It returns 1 for n < 10. What recursive expression correctly handles the other inputs?
  1. n % 10 + digit_count(n // 10)
  2. 1 + digit_count(n % 10)
  3. digit_count(n // 10)
  4. 1 + digit_count(n // 10)
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A recursive algorithm follows T(n)=T(n−1)+c, with constant local work and a fixed base case. What is its tight growth class?
  1. O(log⁡n)
  2. O(n2)
  3. O(n)
  4. O(2n)
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)
  1. Use lo >= hi and and; return False for "abca".
  2. Use lo >= hi and or; return True for "abca".
  3. Use lo == hi and and; return False for "abca".
  4. Use lo <= hi and and; return True for "abca".
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Fast exponentiation calls once on n // 2 and stops at zero. Including the initial and base calls, how many calls compute power(5, 18)?
  1. 4
  2. 6
  3. 5
  4. 7
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A loop-based flattener pops from the end of a stack. It starts with the outer list and pushes every encountered list’s elements in their original order. What values are visited for [3, [1, 8], 6]?
  1. 3, 1, 8, 6
  2. 6, 8, 1, 3
  3. 6, 1, 8, 3
  4. 3, 8, 1, 6
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Naive Fibonacci returns n below 2 and otherwise calls on n - 1 and n - 2. How many calls to fib(1) occur while computing fib(4)?
  1. 3
  2. 2
  3. 4
  4. 5
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What is the flat result of processing [9, [], [4, [6]], 1] from left to right?
  1. [9, [], 4, 6, 1]
  2. [9, [4, 6], 1]
  3. [1, 6, 4, 9]
  4. [9, 4, 6, 1]
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A stable merge sorts records by numeric key. The left half contains (4, "L") and the right half contains (4, "R"), originally in that order. Which record should be taken first, and why?
  1. (4, "R"), because right ties finish the merge.
  2. (4, "L"), because left keys are always smaller.
  3. (4, "L"), because ties preserve original order.
  4. (4, "R"), because equal keys reverse their order.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A fresh memoized Fibonacci computation has 10 cache misses and 7 cache hits. How many requests reach the cache, and how many distinct arguments are computed?
  1. 10 requests and 7 computed arguments
  2. 17 requests and 17 computed arguments
  3. 17 requests and 10 computed arguments
  4. 7 requests and 10 computed arguments
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A list-processing function makes one recursive call on a half-length slice and otherwise does constant work. The input length is a power of two and it stops at length 1. What are its tight time and peak extra-memory growth classes, including slices?
  1. O(log⁡n) time and O(log⁡n) extra memory.
  2. O(nlog⁡n) time and O(n) extra memory.
  3. O(n) time and O(nlog⁡n) extra memory.
  4. O(n) time and O(n) extra memory.
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

For non-negative integers, Euclid’s algorithm returns a when b == 0 and otherwise calls gcd(b, a % b). What quantity guarantees progress when b > 0?
  1. The first argument decreases every time.
  2. The second argument decreases.
  3. The two arguments decrease equally.
  4. The remainder stays equal to b.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A list sum calls itself on xs[1:] until the list is empty. For an original length of 8, how many element references are copied into slices altogether?
  1. 28
  2. 8
  3. 21
  4. 36
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A nested-list flattener uses a shared default 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?
  1. [7]; append each recursive result as one list.
  2. [7, 2, 5]; push nested lists in reverse order.
  3. [2, 5]; replace the stopping condition with length 1.
  4. [2, 5, 7]; create a fresh accumulator for each public call.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A power function stops at exponent zero and otherwise computes the same half power twice with separate recursive calls. For exponent 8, how many calls run, and what change reduces that count?
  1. 15 calls; store one half-power result per call.
  2. 31 calls; multiply by the base on every return.
  3. 31 calls; store one half-power result per call.
  4. 9 calls; subtract one from the exponent per call.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A cached recursive counter uses (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?
  1. Include i in the key along with text and target.
  2. Include only i so positions cannot share a key.
  3. Keep the key and cache only the smallest result.
  4. Keep the key and reverse the recursive call order.
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
  1. 6
  2. 10
  3. 8
  4. 12
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A position-based permutation generator lists every ordering of "mmn" without deduplication. How many output entries and distinct strings does it produce?
  1. 3 entries and 3 distinct strings
  2. 6 entries and 6 distinct strings
  3. 8 entries and 3 distinct strings
  4. 6 entries and 3 distinct strings
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A loop flattener must preserve left-to-right order for [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?
  1. extend(item); output [2, 9, 4, 7].
  2. extend(reversed(item)); output [2, 9, 4, 7].
  3. extend(reversed(item)); output [7, 4, 9, 2].
  4. append(item); output [2, 9, 4, 7].
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

An uncached function makes two calls on n - 1, stops at zero, and keeps only constant-size local state. What are the exact call count and stack depth for input 4?
  1. 15 calls and depth 5
  2. 31 calls and depth 5
  3. 31 calls and depth 4
  4. 15 calls and depth 4
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A service generates every subset of 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?
  1. Both are at least proportional to n!.
  2. Time is linear and output storage is exponential.
  3. Time is exponential and output storage is linear.
  4. Both are at least proportional to n2n.
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)
  1. None
  2. 0
  3. 3
  4. 6
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A length-two sequence generator makes one branch each for "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?
  1. "AB" and "BB"
  2. "CA" and "CB"
  3. "BA" and "BB"
  4. "AC" and "BA"
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A palindrome helper uses indexes correctly, but its wrapper removes spaces and lowercases the text only after calling the helper. It rejects "Step on no pets". What change fixes the intended phrase test without adding work at every recursive level?
  1. Lowercase only the first and last characters after recursion.
  2. Change the base case to accept every two-character string.
  3. Reverse the unprepared string and compare lengths only.
  4. Prepare the text before the helper call and test that result.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Binary search on [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?
  1. lo=0, hi=4
  2. lo=3, hi=4
  3. lo=2, hi=4
  4. lo=3, hi=3
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A program needs Fibonacci at a large first index and then repeatedly requests the same index. A fresh cached recursive version exceeds the recursion limit. What design handles both demands while preserving reuse?
  1. Keep recursion and cache only the final index.
  2. Use a tail-recursive version with an empty cache.
  3. Clear the recursive cache before every request.
  4. Compute with a loop and cache the completed result by index.
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)
  1. 6; return n at the base and recurse on n // 10.
  2. 16; return n at the base and recurse on n - 1.
  3. 6; keep base return 0 and recurse on n // 10.
  4. 8; return n % 10 at the base and recurse on n + 1.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

An algorithm makes two recursive calls on lists of half the length, then scans all elements at that call. What are its tight time and stack-space growth classes if frames keep only constant-size state besides the input references?
  1. O(n) time; O(log⁡n) stack.
  2. O(nlog⁡n) time; O(log⁡n) stack.
  3. O(nlog⁡n) time; O(n) stack.
  4. O(log⁡n) time; O(n) stack.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A slicing-based list sum is rewritten to pass the original list and an increasing index, but still recurses once per element. What changes in its time and stack-space growth?
  1. Time stays O(n2); stack changes to O(1).
  2. Time changes to O(n); stack changes to O(1).
  3. Time changes from O(n2) to O(n); stack stays O(n).
  4. Time changes to O(log⁡n); stack stays O(n).
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Merge [1, 6] with [2, 3, 8]. Immediately after the left list runs out, what is the result so far and what remains to append?
  1. [1, 2, 3]; append [6, 8].
  2. [1, 2, 3, 6]; append [8].
  3. [1, 2, 6]; append [3, 8].
  4. [1, 2, 3, 6, 8]; append [].
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

An algorithm makes two independent half-size recursive calls, then performs a nested loop over all pairs in its current input. With constant-size frame state, what are its tight time and stack-space growth classes?
  1. O(n2log⁡n) time and O(log⁡n) stack.
  2. O(nlog⁡n) time and O(n) stack.
  3. O(n2) time and O(log⁡n) stack.
  4. O(n2) time and O(n) stack.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

60 Key Terms, each with its definition

A

Accumulator
An accumulator stores work completed so far, passing it to the next recursive call or updating it through a loop until the task ends.
An accumulator factorial carries the product forward instead of leaving multiplications waiting.
Append
To append to a Python list is to add one object at its end; a list object is added as one element without unpacking its contents.
Appending [2, 6] to [5] produces [5, [2, 6]], which keeps an extra nesting level.
Auxiliary space
Auxiliary space is additional working memory used by an algorithm, including call frames and temporary lists or tables.
Merge sort needs linear auxiliary list space as well as its logarithmic-depth call stack.

B

Base case
A base case is an input a recursive function answers directly, without needing another recursive call for that input.
An empty-input sum returns 0 in its base case before trying to read a first element.
Binary recursion
Binary recursion makes two recursive child calls in a recursive case, giving the recursion tree branches with two children.
Merge sort uses binary recursion to sort its left and right halves before merging them.
Binary search
Binary search finds a target in sorted input by comparing the middle value and continuing only in the range that can contain the target.
A target smaller than the checked middle value makes binary search discard the right side.

C

Cache hit
A cache hit occurs when a requested key already has a stored answer, allowing the function to return it without computing its body again.
After a Fibonacci value is stored, a later request for that argument becomes a cache hit.
Cache key
A cache key identifies a stored subproblem using all arguments that affect its result, keeping different tasks from sharing an answer.
For binomial coefficients, the cache key needs both the total item count and the selection size.
Cache miss
A cache miss occurs when no answer is stored for the requested key, so the computation must produce the result before it can be reused.
A fresh Fibonacci cache misses the first time it receives each new non-negative argument.
Call stack
The call stack holds the frames of active function calls, with the newest call returning before the waiting call beneath it resumes.
During factorial, the call stack retains each argument and its waiting multiplication.

D

Divide and conquer
Divide and conquer divides a task into smaller tasks of the same kind, solves them recursively, and combines their returned answers.
Merge sort divides the list, sorts both halves, and combines them with a merge.

E

Empty search range
An empty search range has no candidate positions left; with inclusive bounds, its lower index is greater than its upper index.
Binary search returns -1 when an absent target leaves lo > hi after a comparison.
Explicit stack
An explicit stack is a program-managed last-in, first-out collection that stores pending work in place of recursive call bookkeeping.
A loop-based flattener pushes each list in reverse so its explicit stack pops leftmost values first.
Exponential growth
Exponential growth multiplies the amount of work by a fixed factor as input size increases, quickly outgrowing polynomial patterns.
The number of Hanoi moves roughly doubles whenever the stack gains one extra disk.
Extend
To extend a Python list is to add the elements of an iterable individually, which lets a flattened sublist join the current level.
Extending [5] with [2, 6] produces [5, 2, 6], adding two values instead of one list.

F

Fast exponentiation
Fast exponentiation halves a non-negative integer exponent, reuses the half power, and adds one factor of the base for an odd exponent.
A power with exponent 19 needs the exponent-9 result once, then squares it and adds one base factor.
Flattening
Flattening replaces nested list structure with one list of the plain values, preserving their traversal order when order matters.
Flattening [8, [3, 1]] from left to right returns [8, 3, 1] without the inner list.

H

Hashable argument
A hashable argument has a stable hash and equality behavior suitable for a dictionary key, as required by Python’s cache decorators.
An integer is hashable; a tuple of integers can be cached, while a list of integers cannot.
Head
The head of a nonempty string or list is its first item, which can be processed separately from the shorter remaining sequence.
A character counter adds 1 when the head matches its target, then counts the tail.
Helper function
A helper function carries internal work or state, such as a current position, while the public function offers a simpler interface.
A palindrome helper receives two indexes after the wrapper prepares the text once.

I

Iteration
Iteration repeats work through a loop, updating explicit state instead of using recursive function calls to continue the computation.
An iterative factorial updates one product as a loop visits the factors from 2 through the input.

L

Leaf call
A leaf call is a call with no recursive children, usually because it handles a base case and returns its answer directly.
The calls on Fibonacci arguments 0 and 1 are leaves, but still count toward total invocations.
Least recently used cache
A least recently used cache has a size bound and evicts the entry not accessed for the longest time when a new entry needs room.
A bounded lru_cache may recompute an old result after more recent entries displace it.
Leftover elements
Leftover elements are the unused values on one side of a merge after the other side is exhausted, ready to append in their existing order.
Once the right merge input runs out, the unused left values still belong in the result.
Linear recursion
Linear recursion makes one recursive child call per recursive case, forming a chain even when the total running time is not linear.
Binary search has linear recursion in this sense because it follows only one surviving range.
Local work
Local work is the work done by a call outside its recursive children, including operations such as slicing, comparison, and merging.
Copying a tail slice is local work even when the recursive call itself appears on the same line.

M

Memoization
Memoization stores completed function results by their arguments and reuses them when later calls request the same subproblem.
Memoization lets Fibonacci reuse a value that appears in more than one branch of the call tree.
Merge
A merge combines sorted lists by comparing their unused fronts, taking the smaller value, and then copying any remaining values.
Merging [1, 9] and [4, 6] takes 1, 4, and 6 before appending the leftover 9.
Merge sort
Merge sort recursively sorts two halves and merges their sorted results, stopping directly on lists of length zero or one.
Sorting [7, 2, 5, 1] merges the smaller answers [2, 7] and [1, 5].
Multiple recursion
Multiple recursion makes more than two recursive child calls in a recursive case, as when each available item starts another branch.
Permuting four distinct characters starts four smaller permutation calls at the root.
Mutable default argument
A mutable default argument is a changeable object created once at function definition and reused by calls that omit that argument.
A default accumulator list can retain values from an earlier independent call.
Mutual recursion
Mutual recursion occurs when two or more functions call one another in a cycle, with the full call chain following stopping rules.
An evenness test and an oddness test use mutual recursion by alternating on smaller integers.

N

Nested list
A nested list contains lists as elements, possibly at several levels, so its values cannot all be processed by indexing one level alone.
In [4, [2, [7]]], a nested-list sum recurses into each inner list to reach every number.

O

Output-size lower bound
An output-size lower bound is unavoidable work or storage required by the number and size of results an algorithm must produce.
Listing every subset becomes expensive even when its recursive call paths are fairly short.

P

Palindrome
A palindrome is a sequence that reads the same forward and backward; a recursive test compares its ends and then its middle.
The palindrome "level" reduces to "eve" and then to the one-character string "v".
Permutation
A permutation is an ordering of all the input items, with each input position used once; repeated values can yield duplicate orderings.
Four distinct letters have 24 permutations because the available choices decrease at each position.
Prefix
A prefix is the beginning of a result already chosen, carried to a smaller generating call while later positions remain undecided.
A coin-sequence generator extends prefix "HT" with another symbol before reaching a leaf.
Progress toward a base case
Progress toward a base case means each call moves a size measure toward a stopping input that the chain will eventually reach.
Subtracting 1 from a positive integer makes progress toward a base case at zero.
Pure function
A pure function returns a result determined only by its arguments and has no side effects, allowing cached reuse to preserve its behavior.
A numeric counting helper can be pure, while a function that prints changes visible program state.

R

Recurrence
A recurrence expresses a recursive algorithm’s cost using the costs of smaller inputs plus the work performed in the current call.
The recurrence for an index-based sum has one smaller-call cost and constant local work.
Recursion
Recursion solves a problem through function calls on smaller instances of the same problem and combines their answers.
A factorial function uses recursion to build the current product from a smaller factorial.
Recursion depth
Recursion depth is the maximum number of a recursive function’s frames that are active together during one computation.
A chain from argument 5 through a base call on 0 reaches a recursion depth of six frames.
Recursion tree
A recursion tree records every invocation as a node, with child nodes for the recursive calls made directly by their parent.
A Fibonacci recursion tree repeats argument labels when separate branches recompute the same value.
RecursionError
A RecursionError is the Python exception raised when a computation exceeds the current recursion-depth limit.
A long but valid recursive list traversal can raise RecursionError even with a correct base case.
Recursive case
A recursive case solves a current input by calling on one or more smaller inputs and using their answers to construct its result.
The recursive case of factorial multiplies the current argument by the preceding factorial.
Recursive leap of faith
The recursive leap of faith designs a current step by assuming that a call on a smaller input returns its promised correct answer.
For a digit sum, the recursive leap of faith lets the smaller call handle all the leading digits.
Root call
The root call is the original invocation at the top of a recursion tree, from which all later calls in that computation descend.
In a tree for fib(6), the root call has children with arguments 5 and 4.

S

Size measure
A size measure is a quantity that shows how much of a problem remains and decreases toward a base case along recursive calls.
For an index-based traversal, the number of elements still unprocessed is a useful size measure.
Stable sort
A stable sort preserves the original relative order of records whose sort keys are equal, so a merge takes left-side items on ties.
Two records with key 8 keep their earlier-to-later order when every merge handles ties stably.
Stack frame
A stack frame is the record for one active call, preserving its parameters, local bindings, and the return location in its caller.
When a recursive function calls itself on 4 and then 3, the two frames keep separate local bindings even though both use the name n.
Stack overflow
A stack overflow occurs when execution needs more stack capacity than is available; excessive recursive depth is one cause.
A missing stopping case can grow the call chain until stack capacity or a depth guard stops it.
Stack space
Stack space is memory used by simultaneously active call frames, so it follows recursion depth and the state held in each frame.
Naive Fibonacci has linear stack space because only one decreasing path is active at a time.
Subset
A subset selects elements from a set without requiring an order, and can include no elements or all of the original elements.
The empty subset is one valid result when generating all choices of labels to include.

T

Tail
The tail of a nonempty sequence is everything after its first item, giving a smaller input for a head-and-tail recursive step.
For "river", the tail is "iver", and Python slicing creates a new string for it.
Tail call
A tail call is the final action of a function: its result is returned unchanged, with no operation left to perform after it returns.
A call followed by multiplication is not a tail call because that multiplication still has to run.
Time complexity
Time complexity describes how an algorithm’s total work grows with input size, including work across every executed recursive branch.
Counting all nodes and their local costs gives time complexity from a recursion tree.
Towers of Hanoi
Towers of Hanoi is a disk-transfer problem on three pegs in which one disk moves at a time and larger disks never rest on smaller ones.
A recursive Hanoi transfer moves the smaller stack aside before moving its largest disk.

U

Unwinding
Unwinding is the phase in which completed calls return and waiting callers resume, carrying out operations left after their inner calls.
Factorial performs its pending multiplications while unwinding from the base case.

W

Winding
Winding is the phase of recursive execution in which calls descend into smaller inputs and new frames accumulate on the stack.
A summation is winding while it calls on decreasing arguments before reaching zero.
Wrapper function
A wrapper function prepares inputs or supplies initial helper arguments, then calls the function that performs the main recursive work.
A phrase-testing wrapper can remove spaces and lowercase before starting the palindrome helper.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started