Painting the Fence
Medium Accuracy: 27.4% Submissions: 747 Points: 4

Given a fence with n posts and k colors, find out the number of ways of painting the fence such that at most 2 adjacent posts have the same color. Since answer can be large return it modulo 10^9 + 7.

Example 1:

N=3,  K=2 
Output: 6
Explanation: We have following possible combinations:


Example 2:

N=2,  K=4
Output: 16

Your Task:
Since, this is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function countWays() that takes n and k as parameters and returns the number of ways in which the fence can be painted.(modulo 109 + 7)


Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).


1 ≤ N ≤ 105
1 ≤ K ≤ 100


to report an issue on this page.


We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?


All Submissions

My Submissions:

Login to access your submissions.

Output Window