Skip to content
Related Articles
Count ways to reach the n’th stair
• Difficulty Level : Medium
• Last Updated : 26 May, 2021

There are n stairs, a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top. Consider the example shown in the diagram. The value of n is 3. There are 3 ways to reach the top. The diagram is taken from Easier Fibonacci puzzles

Examples:

```Input: n = 1
Output: 1
There is only one way to climb 1 stair

Input: n = 2
Output: 2
There are two ways: (1, 1) and (2)

Input: n = 4
Output: 5
(1, 1, 1, 1), (1, 1, 2), (2, 1, 1), (1, 2, 1), (2, 2) ```

Method 1: The first method uses the technique of recursion to solve this problem.
Approach: We can easily find the recursive nature in the above problem. The person can reach nth stair from either (n-1)th stair or from (n-2)th stair. Hence, for each stair n, we try to find out the number of ways to reach n-1th stair and n-2th stair and add them to give the answer for the nth stair. Therefore the expression for such an approach comes out to be :

`ways(n) = ways(n-1) + ways(n-2)`

The above expression is actually the expression for Fibonacci numbers, but there is one thing to notice, the value of ways(n) is equal to fibonacci(n+1).

```ways(1) = fib(2) = 1
ways(2) = fib(3) = 2
ways(3) = fib(4) = 3```

For a better understanding, let’s refer to the recursion tree below -:

```Input: N = 4

fib(5)
'3'  /        \   '2'
/          \
fib(4)         fib(3)
'2'  /      \ '1'   /      \
/        \     /        \
fib(3)     fib(2)fib(2)      fib(1)
/    \ '1' /   \ '0'
'1' /   '1'\   /     \
/        \ fib(1) fib(0)
fib(2)     fib(1)```

So we can use the function for Fibonacci numbers to find the value of ways(n). Following is C++ implementation of the above idea.

## C++

 `// C++ program to count number of``// ways to reach Nth stair``#include ``using` `namespace` `std;` `// A simple recursive program to``// find N'th fibonacci number``int` `fib(``int` `n)``{``    ``if` `(n <= 1)``        ``return` `n;``    ``return` `fib(n - 1) + fib(n - 2);``}` `// Returns number of ways to``// reach s'th stair``int` `countWays(``int` `s)``{``    ``return` `fib(s + 1);``}` `// Driver C``int` `main()``{``    ``int` `s = 4;` `    ``cout << ``"Number of ways = "` `<< countWays(s);` `    ``return` `0;``}` `// This code is contributed by shubhamsingh10`

## C

 `// C Program to count number of``// ways to reach Nth stair``#include ` `// A simple recursive program to``// find n'th fibonacci number``int` `fib(``int` `n)``{``    ``if` `(n <= 1)``        ``return` `n;``    ``return` `fib(n - 1) + fib(n - 2);``}` `// Returns number of ways to reach s'th stair``int` `countWays(``int` `s)``{``    ``return` `fib(s + 1);``}` `// Driver program to test above functions``int` `main()``{``    ``int` `s = 4;``    ``printf``(``"Number of ways = %d"``, countWays(s));``    ``getchar``();``    ``return` `0;``}`

## Java

 `class` `stairs {``    ``// A simple recursive program to find``    ``// n'th fibonacci number``    ``static` `int` `fib(``int` `n)``    ``{``        ``if` `(n <= ``1``)``            ``return` `n;``        ``return` `fib(n - ``1``) + fib(n - ``2``);``    ``}` `    ``// Returns number of ways to reach s'th stair``    ``static` `int` `countWays(``int` `s)``    ``{``        ``return` `fib(s + ``1``);``    ``}` `    ``/* Driver program to test above function */``    ``public` `static` `void` `main(String args[])``    ``{``        ``int` `s = ``4``;``        ``System.out.println(``"Number of ways = "` `+ countWays(s));``    ``}``} ``/* This code is contributed by Rajat Mishra */`

## Python

 `# Python program to count``# ways to reach nth stair` `# Recursive function to find``# Nth fibonacci number``def` `fib(n):``    ``if` `n <``=` `1``:``        ``return` `n``    ``return` `fib(n``-``1``) ``+` `fib(n``-``2``)` `# Returns no. of ways to``# reach sth stair``def` `countWays(s):``    ``return` `fib(s ``+` `1``)` `# Driver program``s ``=` `4``print` `"Number of ways = "``,``print` `countWays(s)` `# Contributed by Harshit Agrawal`

## C#

 `// C# program to count the``// number of ways to reach``// n'th stair``using` `System;` `class` `GFG {``    ``// A simple recursive``    ``// program to find n'th``    ``// fibonacci number``    ``static` `int` `fib(``int` `n)``    ``{``        ``if` `(n <= 1)``            ``return` `n;``        ``return` `fib(n - 1) + fib(n - 2);``    ``}` `    ``// Returns number of ways``    ``// to reach s'th stair``    ``static` `int` `countWays(``int` `s)``    ``{``        ``return` `fib(s + 1);``    ``}` `    ``// Driver Code``    ``static` `public` `void` `Main()``    ``{``        ``int` `s = 4;``        ``Console.WriteLine(``"Number of ways = "` `+ countWays(s));``    ``}``}` `// This code is contributed``// by akt_mit`

## PHP

 ``

## Javascript

 ``

Output:

`Number of ways = 5`

Complexity Analysis:

• Time Complexity: O(2^n)
The time complexity of the above implementation is exponential (golden ratio raised to power n) due to redundant calculations.It can be optimized to work in O(Logn) time using the previously discussed Fibonacci function optimizations.
• Auxiliary Space: O(1)

Generalization of the Problem
How to count the number of ways if the person can climb up to m stairs for a given value m. For example, if m is 4, the person can climb 1 stair or 2 stairs or 3 stairs or 4 stairs at a time.

Approach: For the generalization of above approach the following recursive relation can be used.

`ways(n, m) = ways(n-1, m) + ways(n-2, m) + ... ways(n-m, m) `

In this approach to reach nth stair, try climbing all possible number of stairs lesser than equal to n from present stair.

Following is the implementation of above recurrence.

## C++

 `// C++ program to count number of ways``// to reach nth stair when a person``// can climb either 1 or 2 stairs at a time``#include ``using` `namespace` `std;` `// A recursive function used by countWays``int` `countWaysUtil(``int` `n, ``int` `m)``{``    ``if` `(n <= 1)``    ``{``        ``return` `n;``    ``}``    ` `    ``int` `res = 0;``    ``for``(``int` `i = 1; i <= m && i <= n; i++)``    ``{``       ``res += countWaysUtil(n - i, m);``    ``}``    ``return` `res;``}` `// Returns number of ways to reach s'th stair``int` `countWays(``int` `s, ``int` `m)``{``    ``return` `countWaysUtil(s + 1, m);``}` `// Driver code``int` `main()``{``    ``int` `s = 4, m = 2;``    ``cout << ``"Number of ways = "` `<< countWays(s, m);` `    ``return` `0;``}` `// This code is contribute by shubhamsingh10`

## C

 `// C program to count number of ways``// to reach nth stair when a person``// can climb either 1 or 2 stairs at a time``#include ` `// A recursive function used by countWays``int` `countWaysUtil(``int` `n, ``int` `m)``{``    ``if` `(n <= 1)``        ``return` `n;``    ``int` `res = 0;``    ``for` `(``int` `i = 1; i <= m && i <= n; i++)``        ``res += countWaysUtil(n - i, m);``    ``return` `res;``}` `// Returns number of ways to reach s'th stair``int` `countWays(``int` `s, ``int` `m)``{``    ``return` `countWaysUtil(s + 1, m);``}` `// Driver program to test above functions-``int` `main()``{``    ``int` `s = 4, m = 2;``    ``printf``(``"Number of ways = %d"``, countWays(s, m));``    ``return` `0;``}`

## Java

 `class` `stairs {``    ``// A recursive function used by countWays``    ``static` `int` `countWaysUtil(``int` `n, ``int` `m)``    ``{``        ``if` `(n <= ``1``)``            ``return` `n;``        ``int` `res = ``0``;``        ``for` `(``int` `i = ``1``; i <= m && i <= n; i++)``            ``res += countWaysUtil(n - i, m);``        ``return` `res;``    ``}` `    ``// Returns number of ways to reach s'th stair``    ``static` `int` `countWays(``int` `s, ``int` `m)``    ``{``        ``return` `countWaysUtil(s + ``1``, m);``    ``}` `    ``/* Driver program to test above function */``    ``public` `static` `void` `main(String args[])``    ``{``        ``int` `s = ``4``, m = ``2``;``        ``System.out.println(``"Number of ways = "``                           ``+ countWays(s, m));``    ``}``} ``/* This code is contributed by Rajat Mishra */`

## Python

 `# A program to count the number of ways``# to reach n'th stair` `# Recursive function used by countWays``def` `countWaysUtil(n, m):``    ``if` `n <``=` `1``:``        ``return` `n``    ``res ``=` `0``    ``i ``=` `1``    ``while` `i<``=` `m ``and` `i<``=` `n:``        ``res ``=` `res ``+` `countWaysUtil(n``-``i, m)``        ``i ``=` `i ``+` `1``    ``return` `res``    ` `# Returns number of ways to reach s'th stair   ``def` `countWays(s, m):``    ``return` `countWaysUtil(s ``+` `1``, m)``    `  `# Driver program``s, m ``=` `4``, ``2``print` `"Number of ways ="``, countWays(s, m)` `# Contributed by Harshit Agrawal`

## PHP

 ``

## Javascript

 ``

Output:

`Number of ways = 5`

Complexity Analysis:

• Time Complexity: O(2^n)
The time complexity of the above implementation is exponential (golden ratio raised to power n) due to redundant calculations. It can be optimized to O(m*n) by using dynamic programming.
• Auxiliary Space: O(1)

Method 2: This method uses the technique of Dynamic Programming to arrive at the solution.

Approach: We create a table res[] in bottom up manner using the following relation:

`res[i] = res[i] + res[i-j] for every (i-j) >= 0`

such that the ith index of the array will contain the number of ways required to reach the ith step considering all the possibilities of climbing (i.e. from 1 to i).

Below code implements the above approach:

## C++

 `// C++ program to count number of ways``// to reach n'th stair when a person``// can climb 1, 2, ..m stairs at a time``#include ``using` `namespace` `std;` `// A recursive function used by countWays``int` `countWaysUtil(``int` `n, ``int` `m)``{``    ``int` `res[n];``    ``res = 1;``    ``res = 1;``    ` `    ``for``(``int` `i = 2; i < n; i++)``    ``{``       ``res[i] = 0;``       ` `       ``for``(``int` `j = 1; j <= m && j <= i; j++)``          ``res[i] += res[i - j];``    ``}``    ``return` `res[n - 1];``}` `// Returns number of ways to reach s'th stair``int` `countWays(``int` `s, ``int` `m)``{``    ``return` `countWaysUtil(s + 1, m);``}` `// Driver code``int` `main()``{``    ``int` `s = 4, m = 2;``    ` `    ``cout << ``"Number of ways = "``         ``<< countWays(s, m);``         ` `    ``return` `0;``}` `// This code is contributed by shubhamsingh10`

## C

 `// A C program to count number of ways``// to reach n'th stair when``// a person can climb 1, 2, ..m stairs at a time``#include ` `// A recursive function used by countWays``int` `countWaysUtil(``int` `n, ``int` `m)``{``    ``int` `res[n];``    ``res = 1;``    ``res = 1;``    ``for` `(``int` `i = 2; i < n; i++) {``        ``res[i] = 0;``        ``for` `(``int` `j = 1; j <= m && j <= i; j++)``            ``res[i] += res[i - j];``    ``}``    ``return` `res[n - 1];``}` `// Returns number of ways to reach s'th stair``int` `countWays(``int` `s, ``int` `m)``{``    ``return` `countWaysUtil(s + 1, m);``}` `// Driver program to test above functions``int` `main()``{``    ``int` `s = 4, m = 2;``    ``printf``(``"Number of ways = %d"``, countWays(s, m));``    ``return` `0;``}`

## Java

 `// Java program to count number of ways``// to reach n't stair when a person``// can climb 1, 2, ..m stairs at a time` `class` `GFG {``    ``// A recursive function used by countWays``    ``static` `int` `countWaysUtil(``int` `n, ``int` `m)``    ``{``        ``int` `res[] = ``new` `int``[n];``        ``res[``0``] = ``1``;``        ``res[``1``] = ``1``;``        ``for` `(``int` `i = ``2``; i < n; i++) {``            ``res[i] = ``0``;``            ``for` `(``int` `j = ``1``; j <= m && j <= i; j++)``                ``res[i] += res[i - j];``        ``}``        ``return` `res[n - ``1``];``    ``}` `    ``// Returns number of ways to reach s'th stair``    ``static` `int` `countWays(``int` `s, ``int` `m)``    ``{``        ``return` `countWaysUtil(s + ``1``, m);``    ``}` `    ``// Driver method``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int` `s = ``4``, m = ``2``;``        ``System.out.println(``"Number of ways = "``                           ``+ countWays(s, m));``    ``}``}`

## Python

 `# A program to count the number of``# ways to reach n'th stair` `# Recursive function used by countWays``def` `countWaysUtil(n, m):``    ``# Creates list res with all elements 0``    ``res ``=` `[``0` `for` `x ``in` `range``(n)]``    ``res[``0``], res[``1``] ``=` `1``, ``1``    ` `    ``for` `i ``in` `range``(``2``, n):``        ``j ``=` `1``        ``while` `j<``=` `m ``and` `j<``=` `i:``            ``res[i] ``=` `res[i] ``+` `res[i``-``j]``            ``j ``=` `j ``+` `1``    ``return` `res[n``-``1``]` `# Returns number of ways to reach s'th stair``def` `countWays(s, m):``    ``return` `countWaysUtil(s ``+` `1``, m)``    ` `# Driver Program``s, m ``=` `4``, ``2``print` `"Number of ways ="``, countWays(s, m)``    ` `# Contributed by Harshit Agrawal`

## C#

 `// C# program to count number``// of ways to reach n'th stair when``// a person can climb 1, 2, ..m``// stairs at a time``using` `System;``class` `GFG {` `    ``// A recursive function``    ``// used by countWays``    ``static` `int` `countWaysUtil(``int` `n, ``int` `m)``    ``{``        ``int``[] res = ``new` `int``[n];``        ``res = 1;``        ``res = 1;``        ``for` `(``int` `i = 2; i < n; i++) {``            ``res[i] = 0;``            ``for` `(``int` `j = 1; j <= m && j <= i; j++)``                ``res[i] += res[i - j];``        ``}``        ``return` `res[n - 1];``    ``}` `    ``// Returns number of ways``    ``// to reach s'th stair``    ``static` `int` `countWays(``int` `s, ``int` `m)``    ``{``        ``return` `countWaysUtil(s + 1, m);``    ``}` `    ``// Driver Code``    ``public` `static` `void` `Main()``    ``{``        ``int` `s = 4, m = 2;``        ``Console.WriteLine(``"Number of ways = "``                          ``+ countWays(s, m));``    ``}``}` `// This code is contributed by anuj_67.`

## PHP

 ``

## Javascript

 ``

Output:

`Number of ways = 5`

Complexity Analysis:

• Time Complexity: O(m*n)
• Auxiliary Space: O(n)

Method 3: The third method uses the technique of Sliding Window to arrive at the solution.
Approach: This method efficiently implements the above Dynamic Programming approach.
In this approach for the ith stair, we keep a window of sum of last m possible stairs from which we can climb to the ith stair. Instead of running an inner loop, we maintain the result of the inner loop in a temporary variable. We remove the elements of the previous window and add the element of the current window and update the sum.

Below code implements the above idea

## C++

 `// A C++ program to count the number of ways``// to reach n'th stair when user``// climb 1 .. m stairs at a time.``// Contributor: rsampaths16``#include ``using` `namespace` `std;` `// Returns number of ways``// to reach s'th stair``int` `countWays(``int` `n, ``int` `m)``{``    ``int` `res[n + 1];``    ``int` `temp = 0;``    ``res = 1;``    ``for` `(``int` `i = 1; i <= n; i++)``    ``{``        ``int` `s = i - m - 1;``        ``int` `e = i - 1;``        ``if` `(s >= 0)``        ``{``            ``temp -= res[s];``        ``}``        ``temp += res[e];``        ``res[i] = temp;``    ``}``    ``return` `res[n];``}` `// Driver Code``int` `main()``{``    ``int` `n = 5, m = 3;``    ``cout << ``"Number of ways = "``         ``<< countWays(n, m);``    ``return` `0;``}` `// This code is contributed by shubhamsingh10`

## C

 `// A C program to count the number of ways``// to reach n'th stair when user``// climb 1 .. m stairs at a time.``// Contributor: rsampaths16``#include ` `// Returns number of ways``// to reach s'th stair``int` `countWays(``int` `n, ``int` `m)``{``    ``int` `res[n + 1];``    ``int` `temp = 0;``    ``res = 1;``    ``for` `(``int` `i = 1; i <= n; i++) {``        ``int` `s = i - m - 1;``        ``int` `e = i - 1;``        ``if` `(s >= 0) {``            ``temp -= res[s];``        ``}``        ``temp += res[e];``        ``res[i] = temp;``    ``}``    ``return` `res[n];``}` `// Driver Code``int` `main()``{``    ``int` `n = 5, m = 3;``    ``printf``(``"Number of ways = %d"``,``           ``countWays(n, m));``    ``return` `0;``}`

## Java

 `// Java program to count number of``// ways to reach n't stair when a``// person can climb 1, 2, ..m``// stairs at a time``class` `GFG{``    ` `// Returns number of ways``// to reach s'th stair``static` `int` `countWays(``int` `n, ``int` `m)``{``    ``int` `res[] = ``new` `int``[n + ``1``];``    ``int` `temp = ``0``;``    ``res[``0``] = ``1``;``    ` `    ``for``(``int` `i = ``1``; i <= n; i++)``    ``{``       ``int` `s = i - m - ``1``;``       ``int` `e = i - ``1``;``       ``if` `(s >= ``0``)``       ``{``           ``temp -= res[s];``       ``}``       ``temp += res[e];``       ``res[i] = temp;``    ``}``    ``return` `res[n];``}``    ` `// Driver Code``public` `static` `void` `main(String[] args)``{``    ``int` `n = ``5``, m = ``3``;``    ``System.out.println(``"Number of ways = "` `+``                       ``countWays(n, m));``}``}` `// This code is contributed by equbalzeeshan`

## Python3

 `# Python3 program to count the number``# of ways to reach n'th stair when``# user climb 1 .. m stairs at a time.` `# Function to count number of ways``# to reach s'th stair``def` `countWays(n, m):``    ` `    ``temp ``=` `0``    ``res ``=` `[``1``]``    ` `    ``for` `i ``in` `range``(``1``, n ``+` `1``):``        ``s ``=` `i ``-` `m ``-` `1``        ``e ``=` `i ``-` `1``        ``if` `(s >``=` `0``):``            ``temp ``-``=` `res[s]``        ``temp ``+``=` `res[e]``        ``res.append(temp)``        ` `    ``return` `res[n]` `# Driver Code``n ``=` `5``m ``=` `3` `print``(``'Number of ways ='``, countWays(n, m))` `# This code is contributed by 31ajaydandge`

## C#

 `// C# program to count number of``// ways to reach n'th stair when``// a person can climb 1, 2, ..m``// stairs at a time``using` `System;``class` `GFG{``    ` `// Returns number of ways``// to reach s'th stair``static` `int` `countWays(``int` `n, ``int` `m)``{``    ``int``[] res = ``new` `int``[n + 1];``    ``int` `temp = 0;``    ``res = 1;``    ` `    ``for``(``int` `i = 1; i <= n; i++)``    ``{``       ``int` `s = i - m - 1;``       ``int` `e = i - 1;``       ``if` `(s >= 0)``       ``{``           ``temp -= res[s];``       ``}``       ``temp += res[e];``       ``res[i] = temp;``    ``}``    ``return` `res[n];``}` `// Driver Code``public` `static` `void` `Main()``{``    ``int` `n = 5, m = 3;``    ``Console.WriteLine(``"Number of ways = "` `+``                      ``countWays(n, m));``}``}` `// This code is contributed by equbalzeeshan`

## Javascript

 ``

Output:

`Number of ways = 13`

Complexity Analysis:

• Time Complexity: O(n)
• Auxiliary Space: O(n)

This article is contributed by Abhishek. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Method 4: The fourth method uses simple mathematics but this is only applicable for this problem if (Order does not matter) while counting steps.

Approach: In This method we simply count the number of sets having 2.

## C++

 `#include ``using` `namespace` `std;` `int` `main() {``    ``int` `n;``    ``n=5;` `    ``// Here n/2 is done to count the number 2's in n``    ``// 1 is added for case where there is no 2.``    ``// eg: if n=4 ans will be 3.``    ``// {1,1,1,1} set having no 2.``    ``// {1,1,2} ans {2,2} (n/2) sets contaning 2.` `    ``cout<<``"Number of ways when order of steps does not matter is : "``<<1+(n/2)<

## Java

 `import` `java.util.*;` `class` `GFG{` `public` `static` `void` `main(String[] args)``{``    ``int` `n;``    ``n = ``5``;``    ` `    ``// Here n/2 is done to count the number 2's``    ``// in n 1 is added for case where there is no 2.``    ``// eg: if n=4 ans will be 3.``    ``// {1,1,1,1} set having no 2.``    ``// {1,1,2} ans {2,2} (n/2) sets contaning 2.``    ``System.out.print(``"Number of ways when order of steps "` `+``                     ``"does not matter is : "` `+ (``1` `+ (n / ``2``)));``}``}` `// This code is contributed by todaysgaurav`

## Python3

 `n ``=` `5` `# Here n/2 is done to count the number 2's in n``# 1 is added for case where there is no 2.``# eg: if n=4 ans will be 3.``# {1,1,1,1} set having no 2.``# {1,1,2} ans {2,2} (n/2) sets contaning 2.``print``(``"Number of ways when order "``      ``"of steps does not matter is : "``, ``1` `+` `(n ``/``/` `2``)) ` `# This code is contributed by rohitsingh07052`

## C#

 `using` `System;` `class` `GFG{``static` `public` `void` `Main()``{``    ``int` `n;``    ``n = 5;``    ` `    ``// Here n/2 is done to count the number 2's``    ``// in n 1 is added for case where there is no 2.``    ``// eg: if n=4 ans will be 3.``    ``// {1,1,1,1} set having no 2.``    ``// {1,1,2} ans {2,2} (n/2) sets contaning 2.``    ``Console.WriteLine(``"Number of ways when order of steps "` `+``                      ``"does not matter is : "` `+ (1 + (n / 2)));` `}``}` `// This code is contributed by Ankita saini`

## Javascript

 ``

Output:

`Number of ways when order of steps does not matter is : 3`

Complexity Analysis:

• Time Complexity : O(1)
• Space Complexity : O(1)

Note: This Method is only applicable for the question Count ways to N’th Stair(Order does not matter) .

Order does not matter means for n = 4  {1 2 1}  ,{2 1 1}  , {1 1 2} are considered same.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live

My Personal Notes arrow_drop_up