Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Data Structures and Algorithms
  • What a Data Structure Is, and How Memory Works
  • Arrays and Dynamic Arrays: Full? Get a Box Twice the Size
  • Linked Lists: A Chain of Clues, Built in Python
  • Stacks: Last In, First Out, With the Undo Button
  • Queues: First In, First Out, With a Ring of Cells
  • Hash Tables: The Name Tells You Where to Look
  • Binary Search Trees: Smaller Left, Bigger Right, Half Gone at Every Look
  • Tree Traversals: In-Order, Pre-Order and Post-Order as a Tour of the House
  • Heaps and Priority Queues: Most Urgent First, Without Searching the Room
  • Graphs and Breadth-First Search (BFS): Fewest Hops, Level by Level
  • Big-O: Reading Cost From Code, With Handshakes and a Guest Book
  • Recursion: Russian Dolls, the Base Case and the Call Stack
  • Linear vs Binary Search: Page by Page, or Open in the Middle
  • Insertion Sort: Take the Next Card and Slide It Left Until It Fits
  • Merge Sort: Split the Pile, Then Merge Two Sorted Piles
  • Quick Sort: Line Up Around One Friend, Then Repeat on Each Side
  • Depth-First Search (DFS): Go Deep, Back Up, Mark Where You've Been
  • The Two Pointers Technique: Find a Pair in One Pass Instead of Every Pair
  • The Sliding Window Technique: One In, One Out
  • Greedy Algorithms: The Best-Looking Choice, Right Now
  • Dynamic Programming: Work It Out Once, Write It Down, Read It Back
  1. Blog
  2. /
  3. Data Structures and Algorithms
  4. /
  5. Algorithms

Dynamic Programming: Work It Out Once, Write It Down, Read It Back

How many ways can Emma climb five stairs, one or two at a time? Plain recursion asks the same small questions again and again; a memo works each one out once. For 30 stairs that is 1,664,079 calls against 57.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Algorithms

What you will learn

  • Break the climbing-stairs problem into smaller copies of itself
  • Explain why plain recursion repeats work and how a memo stops it
  • Add a memo to a recursive Python function and compare call counts
  • Describe top-down and bottom-up dynamic programming and when a memo helps

Before you start

  • Recursion
  • Python lists and classes
  • Big-O notation

Emma has a staircase with five stairs. She climbs one or two stairs at a time, never more. How many different ways can she get to the top?

List them all and look at the last move. In five of the ways, the last move is one stair. In the other three, it's two stairs. Five plus three is eight ways. That gives a neat rule: the ways for five stairs equal the ways for four stairs plus the ways for three stairs. To count five, we ask the same question for four and three, and those ask it for even smaller ones. That's recursion.

Write the answer down

Jack asks Emma, "How many ways to climb three stairs?" Emma counts them all and gets three. Then Tom asks the same question, and Emma counts them all again. Same work, twice. So Emma does something smart: the first time, she writes the answer in a notebook. When Kate asks, Emma just reads it. Three, no counting.

Work it out once, write it down, read it back. In code the notebook is called a memo, and the idea is dynamic programming.

The plain way

class PlainStairs:
    def __init__(self):
        self.calls = 0  # how many times ways() ran

    def ways(self, n):
        self.calls += 1
        if n <= 2:
            return n  # 1 stair: 1 way, 2 stairs: 2 ways
        return self.ways(n - 1) + self.ways(n - 2)

Small staircases answer directly: one stair, one way; two stairs, two ways. Otherwise the last move was one or two stairs, so add ways(n - 1) and ways(n - 2). calls counts every call.

Call tree for ways(5): it calls ways(4) and ways(3); ways(4) calls ways(3) and ways(2); ways(3) calls ways(2) and ways(1). The right-hand ways(3) and its children are repeated work, nine calls in total. With a memo the repeated ways(3) is read back at once, seven calls. ways(5) ways(4) ways(3) ways(2) ways(2) ways(1) ways(3) ways(2) ways(1) repeated: 9 calls in total with a memo, ways(3) is read back: 7 calls
Plain recursion works out ways(3) twice. The memo skips the dashed calls.

Play ways(5): it asks for 4, which asks for 3, which asks for 2 (answer 2) and 1 (answer 1), so 3 stairs is 3. Then 4 also needs 2, so 4 stairs is 5. Now 5 needs ways(3). We worked that out already, but plain recursion doesn't remember, so it does it all again. Eight ways in nine calls, and 3 stairs was worked out twice.

Adding a memo

class MemoStairs:
    def __init__(self):
        self.calls = 0
        self.memo = [0] * 100  # 0 means "not worked out yet"

    def ways(self, n):
        self.calls += 1
        if n <= 2:
            return n
        if self.memo[n] != 0:
            return self.memo[n]  # seen it: remember!
        self.memo[n] = self.ways(n - 1) + self.ways(n - 2)
        return self.memo[n]

Only two lines more. The memo is a list where 0 means "not worked out yet". If memo[n] isn't zero, we've seen this question before, so return the answer at once. Otherwise work it out once and write it into memo[n]. (The list has room for 100 sizes, which is plenty here.)

from plain_stairs import PlainStairs
from memo_stairs import MemoStairs

plain = PlainStairs()
a = plain.ways(5)
print(f"Plain: {a} ways, {plain.calls} calls")

memo = MemoStairs()
b = memo.ways(5)
print(f"Memo: {b} ways, {memo.calls} calls")
Plain: 8 ways, 9 calls
Memo: 8 ways, 7 calls

With the memo, ways(3) is written down the first time. When it comes up again, the page says 3, and no calls happen below it. Every size is worked out only once.

A taller staircase

from plain_stairs import PlainStairs
from memo_stairs import MemoStairs

row = "{} stairs: plain {:>11,} calls, memo {} calls"
for n in (10, 20, 25, 30):
    plain = PlainStairs()
    plain.ways(n)
    memo = MemoStairs()
    memo.ways(n)
    print(row.format(n, plain.calls, memo.calls))
10 stairs: plain         109 calls, memo 17 calls
20 stairs: plain      13,529 calls, memo 37 calls
25 stairs: plain     150,049 calls, memo 47 calls
30 stairs: plain   1,664,079 calls, memo 57 calls

For 30 stairs, the plain way makes over one and a half million calls; the memo way makes 57. Each extra stair makes the plain way about sixty percent more work, because the same small questions keep coming back. The memo adds only two calls per stair.

Filling the notebook from the bottom

There's a second way to use the same notebook. Start at the bottom and never ask a question twice:

StairsRead the two pages beforeWrite
11
22
32 + 13
43 + 25
55 + 38

Eight ways with only three additions, and nothing left waiting. Asking from the top and writing as you go (top-down, the memo above) and filling from the bottom (bottom-up) give the same answer.

What it costs

WayTimeExtra space
Plain recursiongrows like 2n, explodingcall stack only
Top-down with a memoO(n), each size onceone memo cell per size
Bottom-upO(n), one addition per stairone page per size

A little memory buys a huge amount of time. But a memo only pays off when the same small questions come back. Looking up a name in a sorted phone book asks a new question every time, so a notebook helps nobody there.

Where you meet it

  • Spell checkers compare smaller pieces of two words and write each result down.
  • Comparing two versions of a file builds what they share from smaller comparisons.
  • Publishing software picks line breaks so the whole paragraph looks best.
  • Some route finders build the best way to each junction from the junctions before it.

Where a greedy algorithm commits to one choice, dynamic programming keeps the answers to smaller problems and builds the best one from them.

Try it yourself

Ask both classes for 30 stairs and compare the call counts. Then print memo.memo[10] to see an answer the memo remembered.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Data Structures and Algorithms · 21 of 21

Previous
Greedy Algorithms: The Best-Looking Choice, Right Now

Related courses on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Data Structures and Algorithms Concepts: No Coding Needed

How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)

Related posts

Big-O: Reading Cost From Code, With Handshakes and a Guest Book

Big-O asks one question: how do the steps grow when the list grows? Check a school trip sheet for duplicates two ways, handshakes and a guest book, count every step in Python, then grow the list to ten thousand ids and watch 10,000 steps turn into almost 50 million.

Recursion: Russian Dolls, the Base Case and the Call Stack

Recursion means doing the same job on a smaller piece of the problem, and stopping at a base case. Count Emma's Russian dolls with a Python function that calls itself, watch each call wait on the call stack so the answers come back in reverse, then take the base case out and meet RecursionError.

Linear vs Binary Search: Page by Page, or Open in the Middle

Is kite a real word? Page by page takes 11 checks; opening in the middle takes 4. Trace binary search step by step, see a million words answered in 20 checks, and watch it give the wrong answer on an unsorted list.

Insertion Sort: Take the Next Card and Slide It Left Until It Fits

Emma's hand 7, 3, 9, 2, 5 sorted one card at a time in 6 shifts. Trace each card, see why a backwards hand costs the most, why 5,000 shuffled cards need over 6 million shifts, and why a sorted hand needs zero.

On this page

  • Write the answer down
  • The plain way
  • Adding a memo
  • A taller staircase
  • Filling the notebook from the bottom
  • What it costs
  • Where you meet it
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related courses on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Data Structures and Algorithms Concepts: No Coding Needed

How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.