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.
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.
1 <= T <= 10
1 <= N <= 10^6
Time Limit: 1 sec
2
2
3
4
6
For test case 1:
In this case, N = 2, so the total number of ways to color fences using 2 colors is 4
[ [0, 0],
[1, 1],
[0, 1],
[1, 0] ]
Hence, the answer is 4.
For test case 2:
In this case, N = 3, so the total number of ways to color fences using 2 colors is 6.
[ [0, 1, 1],
[1, 0, 0],
[0, 1, 0],
[1, 0, 1],
[0, 0, 1],
[1, 1, 0] ]
Hence, the answer is 6.
2
4
5
10
16
Try to think of a recursive approach.
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:
In this approach, we are going to make a recursive function countWays(N). This function will return the total number of ways to paint N fences.
Algorithm:
O(2^N) where N is the number of fences.
Each function makes two recursive calls, and the total number of recursive calls in the worst case is 2^N. Hence, the overall time complexity is O(2^N).
O(N) where N is the number of fences.
The space complexity O(N) is needed for the recursion stack in the worst case. Hence, the overall space complexity is O(N).