Article start
DSA Course: Interview Patterns and Problem Solving
Module 8: Dynamic Programming

Climbing Stairs: Fibonacci DP Pattern

Convert a small choice tree into a rolling two-state recurrence.

May 29, 2026·25

Learning Outcome

After this lesson, you should be able to turn repeated recursive choices into a simple recurrence with constant memory.

Problem Statement

Given n stairs, return how many distinct ways you can climb to the top when each move can take 1 or 2 steps.

InputOutputWhy
n = 45The valid ways are 1+1+1+1, 1+1+2, 1+2+1, 2+1+1, and 2+2.

Brute Force Approach

Try every sequence of 1-step and 2-step moves recursively. This repeats the same subproblems many times.

Optimized Approach

Let ways[n] = ways[n

  • 1] + ways[n
  • 2]. Keep only the previous two values because each state depends on two earlier states.

Exact Pseudocode

if n <= 2:
  return n
one = 1
two = 2
for step from 3 to n:
  current = one + two
  one = two
  two = current
return two

Reference Code

class Solution:
    def climbStairs(self, n):
        if n <= 2:
            return n

        one, two = 1, 2
        for step in range(3, n + 1):
            current = one + two
            one = two
            two = current
        return two

Sample Dry Run

StepStateResult
Baseways(1)=1, ways(2)=2one=1, two=2
Step 3current = 1 + 2ways(3)=3
Step 4current = 2 + 3ways(4)=5
Returntwo = 5answer = 5

Complexity

MeasureValueReason
TimeO(n)The loop computes each stair count once.
SpaceO(1)Only two rolling values are stored.

Edge Cases

  • n = 1 and n = 2 are base cases.
  • Starting the loop at the wrong step shifts the answer.
  • For very large n, confirm whether modulo is required.

Interview Checklist

  • Define the recurrence before writing code.
  • Use base cases that match the prompt.
  • Update rolling variables in the correct order.

FAQs

Why is this Fibonacci DP?

Each stair can be reached from one step before or two steps before, so the recurrence matches Fibonacci-style growth.

Why not store the full DP array?

You can, but only the previous two states are needed for the next state.

What is the core pattern?

Rolling-state linear DP.

Test your knowledge

Take a quick quiz based on this chapter.

Discussion

0 comments

Sign in to share a question or add to the discussion.
Start the discussion

Ask a question or share what stood out to you.