Skip to the solution
EasyDSA8 min read

How do you solve the climbing stairs problem?

1.1k views

The problem

Question presented to candidate: "You are climbing a staircase with n steps. Each move you climb either 1 or 2 steps. In how many distinct ways can you reach the top? Please write it in Python, start with whatever is simplest, then make it efficient."

What a strong answer should cover:

  • The recurrence from the last move, ways(n) = ways(n - 1) + ways(n - 2), and why the two cases do not overlap.
  • Correct base cases (ways(0) = ways(1) = 1) and the link to Fibonacci.
  • Why plain recursion is exponential, and the progression memo β†’ table β†’ two variables (O(n) time, O(1) space).
  • Generalising to any set of step sizes, or to min cost climbing stairs.
  • Python specifics: tuple assignment for the two-variable shift, int never overflowing (exact climb(92)), and the 1000-frame recursion limit that makes the memo version fail for large n.

Clarifying questions expected:

  • "Are the moves exactly 1 or 2 steps, and does order matter?"
  • "How large can n be β€” do I need 64-bit numbers or a modulo?"

Code / implementation expected: Yes β€” a short Python function, ideally the O(1)-space loop.

  • dp
  • climbing-stairs

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

8 min read Β· 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonFour solutions that agree: naive recursion (with call counts), memo, table and two variables
PythonVariants with the same recipe: any set of step sizes, and min cost climbing stairs
PythonHow big the answer gets: exact values, 32-bit wrap-around and the 2^53 limit

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 4 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

What is the difference between an array and a linked list?

Continue