Bitpath

Lesson 1 · Unit 01

Overlapping subproblems

Why naive recursion repeats itself, and how a memo stops it

11 exercisesabout 3 min

What you practise

  • Repeated work in the call tree
  • A memo makes it linear

Try a question from this lesson

Pick one

To work out fib(5), how many separate times does this function compute fib(2)?

def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)
function fib(n) {
  if (n < 2) return n;
  return fib(n - 1) + fib(n - 2);
}
function fib(n: number): number {
  if (n < 2) return n;
  return fib(n - 1) + fib(n - 2);
}

The idea

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

The same question, asked again

Draw the calls as a tree. fib(3) appears twice and fib(2) three times, and each repeat redoes its whole subtree.

A recursion that keeps asking for the same inputs has overlapping subproblems. That is the signal for dynamic programming: solve each subproblem once and remember the answer.

fib(5)
├─ fib(4)
│  ├─ fib(3)
│  │  ├─ fib(2)
│  │  └─ fib(1)
│  └─ fib(2)
└─ fib(3)
   ├─ fib(2)
   └─ fib(1)
fib(5)
├─ fib(4)
│  ├─ fib(3)
│  │  ├─ fib(2)
│  │  └─ fib(1)
│  └─ fib(2)
└─ fib(3)
   ├─ fib(2)
   └─ fib(1)
fib(5)
├─ fib(4)
│  ├─ fib(3)
│  │  ├─ fib(2)
│  │  └─ fib(1)
│  └─ fib(2)
└─ fib(3)
   ├─ fib(2)
   └─ fib(1)

9 more exercises in the app

  • 2× type the answer
  • 3× multiple choice
  • 1× fill the blanks
  • 1× true or false
  • 1× match the pairs
  • 1× order the lines

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy