Count Ways to Reach Step n With a Given Set of Step Sizes
SquarepointData Scientist · Technical ScreenLast updated
From a Squarepoint technical screen: count the ordered sequences of moves that climb exactly n stairs when every move uses a step size from a given set. It tests careful counting of ordered choices, targets that cannot be reached, and the interviewer's follow-up about reducing the extra space the solution uses.
You are climbing a staircase with n steps, starting on the ground (step 0). Every move offers the same set of choices: you pick one of the allowed step sizes in steps and climb exactly that many steps. Return the number of distinct move sequences that end exactly on step n.
In the interview, a follow-up asked whether the extra space used by the solution could be reduced.
Function Signature
def count_ways(n: int, steps: list[int]) -> int:
Rules
- Order matters: two sequences are different if they have different lengths or choose a different step size at some position, so
1 + 2and2 + 1are different sequences. - The step sizes in a sequence must add up to exactly
n. - Each allowed step size can be used any number of times, and
stepsmay be given in any order. - If no sequence reaches step
nexactly, return0.
Constraints
1 <= n <= 501 <= len(steps) <= 50- The values in
stepsare distinct, and1 <= steps[i] <= 50. - The answer is at most
2^49(reached whenn = 50and every size from 1 to 50 is allowed). That exceeds the 32-bit signed range but stays below2^53, so use 64-bit integers.
Examples
Example 1
Input: n = 4, steps = [1, 2]
Output: 5
The sequences are 1+1+1+1, 1+1+2, 1+2+1, 2+1+1 and 2+2.
Example 2
Input: n = 5, steps = [1, 3, 5]
Output: 5
The sequences are 1+1+1+1+1, 1+1+3, 1+3+1, 3+1+1 and 5.
Example 3
Input: n = 7, steps = [2, 4]
Output: 0
Every allowed size is even, so no sequence adds up to 7.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.