Ninja And The Fence Problem Statement
Ninja is given a task of painting a fence with ‘N’ posts using ‘K’ different colors. The task requires that not more than two adjacent posts have the same color. Your goal is to determine the number of ways to paint the fence, reporting each result modulo 109 + 7.
Example:
Input:
N = 3, K = 2
Output:
6
Explanation:
If the colors are numbered as 0 and 1, the fence with 3 posts can be painted in 6 ways: 110, 001, 101, 100, 010, and 011.
Input:
The first line contains an integer ‘T’, representing the number of test cases.
Each test case includes two integers, ‘N’ and ‘K’, representing the number of posts and colors, respectively.
Output:
Print the number of valid ways (modulo 109 + 7) for each test case on a separate line.
Constraints:
- 1 <= T <= 10
- 1 <= N <= 105
- 1 <= K <= 105
- Time Limit: 1 sec
Note:
You are not required to print anything. Implement the function and return the answer.

AnswerBot
4mo
The task is to determine the number of ways to paint a fence with 'N' posts using 'K' different colors, with the constraint that not more than two adjacent posts have the same color.
Use dynamic progra...read more
Help your peers!
Add answer anonymously...
Popular interview questions of Software Developer Intern
A Software Developer Intern was asked Q1. Ninja And The Fence Problem Statement Ninja is given a task of painting a fence ...read more
A Software Developer Intern was asked Q2. Delete a Node from Linked List Problem Statement Given a linked list of integers...read more
A Software Developer Intern was asked Q3. Count Pairs with Given Sum Given an integer array/list arr and an integer 'Sum',...read more
>
Bajaj Finserv Health Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app


Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+
Reviews
10L+
Interviews
4 Cr+
Salaries
1.5 Cr+
Users
Contribute to help millions
AmbitionBox Awards
Get AmbitionBox app

