TRT
Sign in
easyAdvancedLeetCode#memoization#Fibonacci recurrence

Climbing stairs

Count the ways to climb n stairs one or two steps at a time, first with memoized recursion and then with two variables.

The Runtime Theory Team1 min read
Taught inMemoizationPro — members onlyWhen a recursion solves the same subproblem many times, store each answer the first time and look it up after that. The cost becomes the number of distinct subproblems times the work for each.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inn = 2

out2

inn = 3

out3

inn = 45

out1836311903

You climb n steps, one or two at a time. In how many distinct ways can you reach the top?

Before you code

The last move was either one step or two, so the count is the sum of the counts for n − 1 and n − 2. Write it as recursion, see it slow down around n = 35, then memoize.

Hints

  1. Base cases: one way for n = 0 (or n = 1) and two for n = 2.
  2. Memoize with a dictionary or functools.cache.
  3. Then keep only the last two values in a loop: O(n) time, O(1) space.

Production & complexity notes

When solving Climbing stairs on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Memoization to reinforce the underlying pattern.

What it practices

Overlapping subproblems and the cache that removes them, from Memoization.

Not started

Sign in to save your learning progress.

Sign in to save