Grammarly VO Interview Coding Question: Climbing Stairs

15 Views
No Comments

Climbing Stairs

Description

You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

You can assume n is greater than 0.

Example 1:

Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

This is a classic counting DP problem: the number of ways to reach step n depends only on the number of ways to reach the previous one and two steps, since the last move can be either 1 or 2 steps. The recurrence is dp[i] = dp[i-1] + dp[i-2], and it can be implemented with O(1) extra space using two rolling variables. The examples n = 2 and n = 3 produce 2 and 3 ways, matching the Fibonacci-style pattern.

END
 0