Given a fence with n posts and k colors, the task is to find out the number of ways of painting the fence so that not more than two consecutive posts have the same color.
Examples:
Input: n = 2, k = 4 Output: 16 Explanation: We have 4 colors and 2 posts. Ways when both posts have same color: 4 Ways when both posts have diff color: 4(choices for 1st post) * 3(choices for 2nd post) = 12
Input: n = 3, k = 2 Output: 6 Explanation: The following image depicts the 6 possible ways of painting 3 posts with 2 colors:
The idea is to define our solution in terms of two choices: painting the last post adifferent color from the previous one or painting the last two posts the same color. This gives us the recurrence relation:
Case 1: Different Color for the Last Post If we paint the last post a different color from the one before it, we have k-1 choices (all colors except the previous post’s color). This means the number of ways to paint the first n-1 posts is multiplied by k-1.
Case 2: Same Color for the Last Two Posts If the last two posts are the same color, they must differ from the post before them (the third-last post). Thus, we have k-1 choices for the last two posts, and the number of ways to paint the first n-2 posts is given by countWays(n-2).
Consider the following image, in which c, c' and c'' are the respective colors of posts i, i-1, and i-2.
C++
// C++ program for Painting Fence Algorithm// using recursion#include<bits/stdc++.h>usingnamespacestd;// Returns count of ways to color k postsintcountWays(intn,intk){// base casesif(n==1)returnk;if(n==2)returnk*k;// Ways in which last fence // is of different color.intcnt1=countWays(n-1,k)*(k-1);// Ways in which last 2 fences// are of same color.intcnt2=countWays(n-2,k)*(k-1);returncnt1+cnt2;}intmain(){intn=3,k=2;cout<<countWays(n,k)<<endl;return0;}
Java
// Java program for Painting Fence Algorithm// using recursionclassGfG{// Returns count of ways to color k postsstaticintcountWays(intn,intk){// base casesif(n==1)returnk;if(n==2)returnk*k;// Ways in which last fence // is of different color.intcnt1=countWays(n-1,k)*(k-1);// Ways in which last 2 fences// are of same color.intcnt2=countWays(n-2,k)*(k-1);returncnt1+cnt2;}publicstaticvoidmain(String[]args){intn=3,k=2;System.out.println(countWays(n,k));}}
Python
# Python program for Painting Fence Algorithm# using recursion# Returns count of ways to color k postsdefcountWays(n,k):# base casesifn==1:returnkifn==2:returnk*k# Ways in which last fence # is of different color.cnt1=countWays(n-1,k)*(k-1)# Ways in which last 2 fences# are of same color.cnt2=countWays(n-2,k)*(k-1)returncnt1+cnt2if__name__=="__main__":n=3k=2print(countWays(n,k))
C#
// C# program for Painting Fence// using recursionusingSystem;classGfG{// Returns count of ways to color k postsstaticintcountWays(intn,intk){// base casesif(n==1)returnk;if(n==2)returnk*k;// Ways in which last fence // is of different color.intcnt1=countWays(n-1,k)*(k-1);// Ways in which last 2 fences// are of same color.intcnt2=countWays(n-2,k)*(k-1);returncnt1+cnt2;}staticvoidMain(string[]args){intn=3,k=2;Console.WriteLine(countWays(n,k));}}
JavaScript
// JavaScript program for Painting// Fence using recursion// Returns count of ways to color k postsfunctioncountWays(n,k){// base casesif(n===1)returnk;if(n===2)returnk*k;// Ways in which last fence // is of different color.letcnt1=countWays(n-1,k)*(k-1);// Ways in which last 2 fences// are of same color.letcnt2=countWays(n-2,k)*(k-1);returncnt1+cnt2;}letn=3,k=2;console.log(countWays(n,k));
Output
6
Using Top-Down DP (Memoization) – O(n) Time and O(n) Space
If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming:
1. Optimal Substructure:
Number of ways to paint the nth fence, i.e., countWays(n), depends on the solutions of the subproblems countWays(n-1) , and countWays(n-2). By adding these optimal substructures, we can efficiently calculate the total number of ways to reach the nth fence.
2. Overlapping Subproblems:
While applying a recursive approach in this problem, we notice that certain subproblems are computed multiple times. For example, when calculating countWays(4), we recursively calculate countWays(3) and countWays(2) which in turn will recursively compute countWays(2) again. This redundancy leads to overlapping subproblems.
There is only one parameter that changes in the recursive solution and it can go from 1 to n. So we create a 1D array of size n+1 for memoization.
We initialize this array as -1 to indicate nothing is computed initially.
Now we modify our recursive solution to first check if the value is -1, then only make recursive calls. This way, we avoid re-computations of the same subproblems.
C++
// C++ program for Painting Fence Algorithm// using memoization#include<bits/stdc++.h>usingnamespacestd;intcountWaysRecur(intn,intk,vector<int>&memo){// base casesif(n==1)returnk;if(n==2)returnk*k;if(memo[n]!=-1)returnmemo[n];// Ways in which last fence // is of different color.intcnt1=countWaysRecur(n-1,k,memo)*(k-1);// Ways in which last 2 fences// are of same color.intcnt2=countWaysRecur(n-2,k,memo)*(k-1);returnmemo[n]=cnt1+cnt2;}// Returns count of ways to color k postsintcountWays(intn,intk){vector<int>memo(n+1,-1);returncountWaysRecur(n,k,memo);}intmain(){intn=3,k=2;cout<<countWays(n,k)<<endl;return0;}
Java
// Java program for Painting Fence Algorithm// using memoizationimportjava.util.Arrays;classGfG{staticintcountWaysRecur(intn,intk,int[]memo){// base casesif(n==1)returnk;if(n==2)returnk*k;if(memo[n]!=-1)returnmemo[n];// Ways in which last fence // is of different color.intcnt1=countWaysRecur(n-1,k,memo)*(k-1);// Ways in which last 2 fences// are of same color.intcnt2=countWaysRecur(n-2,k,memo)*(k-1);returnmemo[n]=cnt1+cnt2;}// Returns count of ways to color k postsstaticintcountWays(intn,intk){int[]memo=newint[n+1];Arrays.fill(memo,-1);returncountWaysRecur(n,k,memo);}publicstaticvoidmain(String[]args){intn=3,k=2;System.out.println(countWays(n,k));}}
Python
# Python program for Painting Fence Algorithm# using memoizationdefcountWaysRecur(n,k,memo):# base casesifn==1:returnkifn==2:returnk*kifmemo[n]!=-1:returnmemo[n]# Ways in which last fence # is of different color.cnt1=countWaysRecur(n-1,k,memo)*(k-1)# Ways in which last 2 fences# are of same color.cnt2=countWaysRecur(n-2,k,memo)*(k-1)memo[n]=cnt1+cnt2returnmemo[n]# Returns count of ways to color k postsdefcountWays(n,k):memo=[-1]*(n+1)returncountWaysRecur(n,k,memo)if__name__=="__main__":n=3k=2print(countWays(n,k))
C#
// C# program for Painting Fence Algorithm// using memoizationusingSystem;classGfG{staticintcountWaysRecur(intn,intk,int[]memo){// base casesif(n==1)returnk;if(n==2)returnk*k;if(memo[n]!=-1)returnmemo[n];// Ways in which last fence // is of different color.intcnt1=countWaysRecur(n-1,k,memo)*(k-1);// Ways in which last 2 fences// are of same color.intcnt2=countWaysRecur(n-2,k,memo)*(k-1);returnmemo[n]=cnt1+cnt2;}// Returns count of ways to color k postsstaticintcountWays(intn,intk){int[]memo=newint[n+1];Array.Fill(memo,-1);returncountWaysRecur(n,k,memo);}staticvoidMain(string[]args){intn=3,k=2;Console.WriteLine(countWays(n,k));}}
JavaScript
// JavaScript program for Painting Fence Algorithm// using memoizationfunctioncountWaysRecur(n,k,memo){// base casesif(n===1)returnk;if(n===2)returnk*k;if(memo[n]!==-1)returnmemo[n];// Ways in which last fence // is of different color.letcnt1=countWaysRecur(n-1,k,memo)*(k-1);// Ways in which last 2 fences// are of same color.letcnt2=countWaysRecur(n-2,k,memo)*(k-1);memo[n]=cnt1+cnt2;returnmemo[n];}// Returns count of ways to color k postsfunctioncountWays(n,k){letmemo=newArray(n+1).fill(-1);returncountWaysRecur(n,k,memo);}letn=3,k=2;console.log(countWays(n,k));
Output
6
Using Bottom-Up DP (Tabulation) – O(n) Time and O(n) Space
The idea is to create a 1-D array, fill values for first two fences and compute the values from 3 to n using the previous two results. For i = 3 to n, do dp[i] = dp[i-1]*(k-1) + dp[i-2]*(k-1).
C++
// C++ program for Painting Fence Algorithm// using tabulation#include<bits/stdc++.h>usingnamespacestd;// Returns count of ways to color k postsintcountWays(intn,intk){// base casesif(n==1)returnk;if(n==2)returnk*k;vector<int>dp(n+1);// Fill value for 1 and 2 fencesdp[1]=k;dp[2]=k*k;for(inti=3;i<=n;i++){dp[i]=dp[i-1]*(k-1)+dp[i-2]*(k-1);}returndp[n];}intmain(){intn=3,k=2;cout<<countWays(n,k)<<endl;return0;}
Java
// Java program for Painting Fence Algorithm// using tabulationimportjava.util.Arrays;classGfG{// Returns count of ways to color k postsstaticintcountWays(intn,intk){// base casesif(n==1)returnk;if(n==2)returnk*k;int[]dp=newint[n+1];// Fill value for 1 and 2 fencesdp[1]=k;dp[2]=k*k;for(inti=3;i<=n;i++){dp[i]=dp[i-1]*(k-1)+dp[i-2]*(k-1);}returndp[n];}publicstaticvoidmain(String[]args){intn=3,k=2;System.out.println(countWays(n,k));}}
Python
# Python program for Painting Fence Algorithm# using tabulationdefcountWays(n,k):# base casesifn==1:returnkifn==2:returnk*kdp=[0]*(n+1)# Fill value for 1 and 2 fencesdp[1]=kdp[2]=k*kforiinrange(3,n+1):dp[i]=dp[i-1]*(k-1)+dp[i-2]*(k-1)returndp[n]if__name__=="__main__":n=3k=2print(countWays(n,k))
C#
// C# program for Painting Fence Algorithm// using tabulationusingSystem;classGfG{// Returns count of ways to color k postsstaticintcountWays(intn,intk){// base casesif(n==1)returnk;if(n==2)returnk*k;int[]dp=newint[n+1];// Fill value for 1 and 2 fencesdp[1]=k;dp[2]=k*k;for(inti=3;i<=n;i++){dp[i]=dp[i-1]*(k-1)+dp[i-2]*(k-1);}returndp[n];}staticvoidMain(string[]args){intn=3,k=2;Console.WriteLine(countWays(n,k));}}
JavaScript
// JavaScript program for Painting Fence Algorithm// using tabulationfunctioncountWays(n,k){// base casesif(n===1)returnk;if(n===2)returnk*k;letdp=newArray(n+1).fill(0);// Fill value for 1 and 2 fencesdp[1]=k;dp[2]=k*k;for(leti=3;i<=n;i++){dp[i]=dp[i-1]*(k-1)+dp[i-2]*(k-1);}returndp[n];}letn=3,k=2;console.log(countWays(n,k));
Output
6
Using Space Optimized DP – O(n) Time and O(1) Space
The idea is to store only the previous two computed values. We can observe that for a given fence, only the result of last three fences are needed. So only store these three values and update them after each step.
C++
// C++ program for Painting Fence Algorithm// using space optimised#include<bits/stdc++.h>usingnamespacestd;// Returns count of ways to color k postsintcountWays(intn,intk){// base casesif(n==1)returnk;if(n==2)returnk*k;// Fill value for 1 and 2 fencesintprev2=k;intprev1=k*k;for(inti=3;i<=n;i++){intcurr=prev1*(k-1)+prev2*(k-1);// update the valuesprev2=prev1;prev1=curr;}returnprev1;}intmain(){intn=3,k=2;cout<<countWays(n,k)<<endl;return0;}
Java
// Java program for Painting Fence Algorithm// using space optimisedclassGfG{// Returns count of ways to color k postsstaticintcountWays(intn,intk){// base casesif(n==1)returnk;if(n==2)returnk*k;// Fill value for 1 and 2 fencesintprev2=k;intprev1=k*k;for(inti=3;i<=n;i++){intcurr=prev1*(k-1)+prev2*(k-1);// update the valuesprev2=prev1;prev1=curr;}returnprev1;}publicstaticvoidmain(String[]args){intn=3,k=2;System.out.println(countWays(n,k));}}
Python
# Python program for Painting Fence Algorithm# using space optimiseddefcountWays(n,k):# base casesifn==1:returnkifn==2:returnk*k# Fill value for 1 and 2 fencesprev2=kprev1=k*kforiinrange(3,n+1):curr=prev1*(k-1)+prev2*(k-1)# update the valuesprev2=prev1prev1=currreturnprev1if__name__=="__main__":n=3k=2print(countWays(n,k))
C#
// C# program for Painting Fence Algorithm// using space optimisedusingSystem;classGfG{// Returns count of ways to color k postsstaticintcountWays(intn,intk){// base casesif(n==1)returnk;if(n==2)returnk*k;// Fill value for 1 and 2 fencesintprev2=k;intprev1=k*k;for(inti=3;i<=n;i++){intcurr=prev1*(k-1)+prev2*(k-1);// update the valuesprev2=prev1;prev1=curr;}returnprev1;}staticvoidMain(string[]args){intn=3,k=2;Console.WriteLine(countWays(n,k));}}
JavaScript
// JavaScript program for Painting Fence Algorithm// using space optimisedfunctioncountWays(n,k){// base casesif(n===1)returnk;if(n===2)returnk*k;// Fill value for 1 and 2 fencesletprev2=k;letprev1=k*k;for(leti=3;i<=n;i++){letcurr=prev1*(k-1)+prev2*(k-1);// update the valuesprev2=prev1;prev1=curr;}returnprev1;}letn=3,k=2;console.log(countWays(n,k));