A staircase has n steps and you start at the bottom. Each move takes you up either 1 step or 2 steps.
Count how many different sequences of moves land you exactly on step n. Two sequences are different if the moves differ in size or in order, so 1 then 2 is not the same as 2 then 1.
Example 1
Input: n = 4 Output: 5 Why: 1+1+1+1, 2+2, and three orders of 2+1+1
2 more examples and the constraints
Example 2
Input: n = 6 Output: 13 Why: 5 ways end with a 2-step, 8 ways end with a 1-step
Example 3
Input: n = 1 Output: 1 Why: a single 1-step is the only option
Constraints
- 1 ≤ n ≤ 45
- The answer for n = 45 is 1,836,311,903, which still fits in a 32-bit signed integer
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Plain recursionO(2ⁿ)
- Recursion with memoO(n)
- Bottom-up, two variablesO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 45 | Verdict |
|---|---|---|---|
| Plain recursion | O(2ⁿ) | Shows the recurrence; too slow | |
| Recursion with memo | O(n) | Passes; O(n) memory | |
| Bottom-up, two variables | O(n) | Best; constant memory |
n = number of steps in the staircase.
Edge cases to test
- One step. n = 1 gives 1. The loop in the bottom-up version must not run at all.
- Two steps. n = 2 gives 2: two 1-steps, or one 2-step.
- Largest n. n = 45 gives 1,836,311,903. It fits in a 32-bit int, but n = 46 would not.
- Order matters. For n = 3, 1+2 and 2+1 are two separate ways, so the answer is 3, not 2.
Common mistakes
- Using ways(0) = 0 as the base case, which makes every answer wrong; standing still at the bottom is one way.
- Submitting the plain recursion, which times out long before n = 45.
- Counting sets of moves instead of sequences, so 1+2 and 2+1 are counted once.
How to talk through it
- 1Clarify. Does the order of moves matter? Is n at least 1? How large can n get?
- 2Find the recurrence. Look at the last move: it is a 1 or a 2, so ways(n) = ways(n − 1) + ways(n − 2).
- 3Say why plain recursion is slow. The same steps are solved again and again; the call tree grows exponentially.
- 4Fix it, then shrink it. Memoise to get O(n), then fill bottom-up and keep only the last two values for O(1) space.
- 5Test out loud. Run n = 1, n = 2 and n = 4 by hand: 1, 2 and 5.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?