Coding Problem 6: Count possible ways to construct buildings [GFG - Problem Solving]

 There is a road passing through a city with N plots on both sides of the road. Plots are arranged in a straight line on either side of the road. Determine the total number of ways to construct buildings in these plots, ensuring that no two buildings are adjacent to each other. Specifically, buildings on opposite sides of the road cannot be adjacent.

Using * to represent a plot and || for the road, the arrangement for N = 3 can be visualized as follows: * * * || * * *.

Note: As the answer can be very large, print it mod 109+7.

Example 1:

Input: N = 1
Output: 4
Explanation: 
Possible ways for the arrangement are
B||*, *||B, B||B, *||*
where B represents a building.

Example 2:

Input: N = 3
Output: 25
Explanation: 
Possible ways for one side are BSS, BSB, SSS, SBS,
SSB where B represents a building and S represents an empty space. Pairing up with
possibilities on the other side of the road,
total possible ways are 25.

Your Task:
You don't need to read or print anything. Your task is to complete the function TotalWays() which takes N as input parameter and returns the total possible ways modulo 109 + 7.

 

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

 

Constraints:
1 <= N <= 100000



Solution : 

package com.coding.problems.gfg;

public class ConstructBuilding {


//User function Template for Java
public int TotalWays(int N) {
// Code here
long mod = 1000000007;
if (N == 1) {
return 4;
}
long first = 1;
long second = 1;
long prev_f = 0, prev_s = 0;
for (int i = 2; i <= N; i++) {//normal fibonacci
prev_f = second;
second = (first + second) % mod;

first = prev_f;
prev_s = second;
}
long ans = ((prev_f + prev_s));
return (int) ((ans * ans) % mod);
}
}

Comments

Popular posts from this blog

Primitive Data Types in java

let - Keyword in JavaScript (Block scope)

Coding Problem 4: Smallest window containing 0, 1 and 2 [GFG - Problem Solving]