Painting Fences

You are given ‘N’ fences. Your task is to find the total number of ways to paint fences using 2 colors only such that at most 2 adjacent fences are painted with the same color.

As the answer can be too large, return the answer modulo 10^9 + 7.

For Example:
Consider If N = 2, then there can be 4 different ways to color fences such that at most 2 adjacent fences have the same color-:
[ [0, 1],
  [1, 0],
  [1, 1],
  [0, 0] ]
Hence, the answer is 4.
Input Format:
The first line contains a single integer ‘T’ representing the number of test cases.

The first line of each test case contains a single integer ‘N’, representing the number of fences.
Output Format:
For each test case, print a single integer denoting the number of ways to paint the fences modulo 10^9 + 7.

Print the output of each test case in a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
1 <= N <= 10^6

Time Limit: 1 sec
CodingNinjas
author
2y
Dynamic Programming

We will maintain two variables prev and curr, to find the total number of ways to paint the fences. We will initialize prev and curr as 2. We will traverse ind from 2 to N.

  1. We will f...read more
CodingNinjas
author
2y

First I had couple of greedy solutions in mind, later on analysis I tried applying dynamic programming approach.
It was working.

CodingNinjas
author
2y
Recursion

The idea is to use a recursive approach to find the total number of ways to paint the fences. Let us consider the two colors are black and white.

We have to think about two possibilities:

  1. If t...read more
CodingNinjas
author
2y
Memoization

As discussed in the previous approach, we are using a recursive approach to find the total number of ways to paint the fences. In this approach, we will use memoization to reduce our time c...read more

Add answer anonymously...
PayPal Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter