Count possible ways to construct buildings | Returns count of possible ways for N sections ; Base case ; 2 for one side and 4 for two sides ; countB is count of ways with a building at the end countS is count of ways with a space at the end prev_countB and prev_countS are previous values of countB and countS respectively . Initialize countB and countS for one side ; Use the above recursive formula for calculating countB and countS using previous values ; Result for one side is sum of ways ending with building and ending with space ; Result for 2 sides is square of result for one side ; Driver code
function countWays ( N ) { if ( N == 1 ) return 4 ; let countB = 1 , countS = 1 , prev_countB , prev_countS ; for ( let i = 2 ; i <= N ; i ++ ) { prev_countB = countB ; prev_countS = countS ; countS = prev_countB + prev_countS ; countB = prev_countS ; } let result = countS + countB ; return ( result * result ) ; } N = 3 ; document . write ( " " + N + " " + countWays ( N ) ) ;