Menu

Sign in to track your progress and unlock all features.

Theme style

Log in
01. Compute Fibonacci with memoizationE02. Count ways to climb stairsE03. Find the minimum cost to climb stairsE

Problem No 2

Count ways to climb stairs

Easy

10 minute session

Summary

Count the number of distinct ways to climb n stairs taking 1 or 2 steps at a time using dynamic programming.

Problem statement

You are climbing a staircase that has n steps. You can take either 1 step or 2 steps at a time. How many distinct ways are there to reach the top? For example: - If n = 1, there is 1 way: [1] - If n = 2, there are 2 ways: [1+1], [2] Requirements: - Implement climb_ways(n) where n is a non-negative integer. - Return the number of distinct ways to climb to the top using 1- or 2-step moves. - Use dynamic programming (memoization or tabulation) for efficiency. - Define climb_ways(0) = 1 (one way: take no steps). - For negative n, raise a ValueError.

Task

Implement climb_ways(n) that returns how many distinct sequences of 1- and 2-step moves reach the top of n stairs using memoization or tabulation.

Examples

Example: n = 5

Input

climb_ways(5)

Output

8

Explanation

Ways correspond to Fibonacci numbers: climb_ways(5) = 8

Input format

A single non-negative integer n passed as an argument to climb_ways(n).

Output format

An integer: the number of distinct ways to reach step n using 1- and 2-step moves.

Constraints

0 <= n <= 1000. Result grows exponentially but fits in Python int for typical interview ranges. Use DP to achieve O(n) time and O(1) or O(n) space.

Samples

Sample input 0

climb_ways(2)

Sample output 0

2

Explanation 0

Two ways: [1+1] and [2]

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

03:48 PM

Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.