Ninja And The Fence

Ninja has given a fence, and he gave a task to paint this fence. The fence has 'N' posts, and Ninja has 'K' colors. Ninja wants to paint the fence so that not more than two adjacent posts have the same color.

Ninja wonders how many ways are there to do the above task, so he asked for your help.

Your task is to find the number of ways Ninja can paint the fence. Print the answer modulo 10^9 + 7.

Example:
Input: 'N' = 3, 'K' = 2
Output: 6

Say we have the colors with the numbers 1 and 0. We can paint the fence with 3 posts with the following different combinations.

110
001
101
100
010
011
Input Format :
The first line of input contains an integer 'T', denoting the number of test cases. 

Each test case will contain two integers 'N' and 'K' denoting the number of posts on the fence and the number of colors Ninja has.
Output format :
For each test case, print the number of ways modulo 10^9 + 7 to paint the fence.

Output for each test case will be printed in a separate line.
Note :
You don't need to print anything. It has already been taken care of. Just implement the given function.
Constraints :
1 <= ‘T’ <= 10
1 <= 'N' <= 10^5
1 <= 'K' <= 10^5
Time Limit: 1 sec
CodingNinjas
author
2y
Recursive Brute Force

Approach: Say the function 'solve(n)' calculates how many ways to paint a fence with 'N' points and 'K' colors. we want to figure out the relationship between 'solve(n)' for 'N' ...read more

CodingNinjas
author
2y
Recursive DP Solution

Approach: In the above approach, we are repetitively calling the recursive calls; instead, we can store the partial results in the 'DP' array and use it for further recursive cal...read more

CodingNinjas
author
2y
Iterative DP Solution

Approach: In the above approach, we will do the same as we did in the previous approach, but instead of calling recursion, we will do it iteratively by calculating the results fr...read more

CodingNinjas
author
2y
Iterative Constant Space Solution

Approach: In the above approach, we will space optimize the above solution; instead of using the 'DP' table we will use the variable. it will make it a constant time ...read more

Add answer anonymously...
Bajaj Finserv Health Software Developer Intern 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