Climbing Stairs

Count distinct ways to climb n stairs (1 or 2 steps at a time).

Easy

Examples

Example 1: n = 3 → 3 (1+1+1, 1+2, 2+1)

Implementation

Ruby

  # ----------------------------------------
  # 1. Climbing Stairs - Basic DP Introduction
  #
  # Problem: You're climbing a staircase with n steps. Each time you can climb 1 or 2 steps.
  # How many distinct ways can you climb to the top?
  #
  # Input: n = 3
  # Output: 3 (1+1+1, 1+2, 2+1)
  #
  # Time Complexity: O(n)
  # Space Complexity: O(1)
  # ----------------------------------------
  def climbing_stairs(n)
    return 1 if n <= 1
    
    prev2, prev1 = 1, 1
    
    (2..n).each do |i|
      current = prev1 + prev2
      puts "Step #{i}: ways = #{prev1} + #{prev2} = #{current}"
      prev2, prev1 = prev1, current
    end
    
    puts "Total ways to climb #{n} stairs: #{prev1}"
    prev1

Complexity Analysis

Time Complexity:
O(n)?
Why O(n)?
We calculate each step once from 2 to n
Instead of naive recursion (exponential), we use bottom-up DP to compute each step exactly once.
Example: For n=50, we do 48 iterations instead of 2^50 recursive calls
Space Complexity:
O(1)?
Why O(1)?
Only storing the last two values
We optimize space by only keeping prev2 and prev1 instead of an entire DP array.
Example: Uses same memory for n=10 or n=10,000

Problem Details

Category: Dynamic Programming
Difficulty: Easy
Module: DynamicProgramming
Method: climbing_stairs
← Back to Dynamic Programming