Ways to paint stairs with two colors such that two adjacent are not yellow


Given n stairs and we have 2 colour yellow and green the task is that we have to paint given stairs by given colour with condition is that we cannot paints two yellow steps directly after each other.


Input : n = 1
Output : 2
A single stair can be colored either
as green or yellow.

Input : n = 3
Output : 5

Case 1: When we have 1 stair, we can paint either yellow or green.
Case 2: When we have 2 stairs, we can paint first stair by either yellow or green but for next stair we can only paint by green because we cannot paint two yellow steps directly after each other. So total cases are three YG, GG, GY.
Case 3: When we have 3 stairs then we can paint it by in 5 ways.

If we take a closer look, we can notice that it follows Fibonacci Series.


// C++ Program to find the number of ways to paint stairs
#include <bits/stdc++.h>
using namespace std;

// Function to find the number of ways
int ways(int n)
    int W[n + 1];

    // take base case for 1 and 2
    W[1] = 2;
    W[2] = 3;

    for (int i = 3; i <= n; i++) 
        W[i] = W[i - 1] + W[i - 2];
    return W[n];

// Driven code
int main()
    int n = 3;
    printf("%d", ways(n));
    return 0;


# Python3 code to find the number
# of ways to paint stairs

# Function to find the number of ways
def ways( n ):
    W = list()
    # take base case for 1 and 2
    i = 3
    while i <= n:
        W.append(W[i - 1] + W[i - 2])
        i = i + 1
    return W[n]

# Driver code
n = 3

# This code is contributed by "Sharad_Bhardwaj".


Time Complexity: O(n)
Extra Space: O(n)

We can solve this problem in O(Log n) time also using matrix exponentiation solution for n-th Fibonacci Number.

This article is contributed by DANISH_RAZA. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:

3 Average Difficulty : 3/5.0
Based on 1 vote(s)

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.