Count Number of Ways to Place Houses Problem
Description
LeetCode Problem 2320.
There is a street with n * 2 plots, where there are n plots on each side of the street. The plots on each side are numbered from 1 to n. On each plot, a house can be placed.
Return the number of ways houses can be placed such that no two houses are adjacent to each other on the same side of the street. Since the answer may be very large, return it modulo 10^9 + 7.
Note that if a house is placed on the i^th plot on one side of the street, a house can also be placed on the i^th plot on the other side of the street.
Example 1:
Input: n = 1
Output: 4
Explanation:
Possible arrangements:
1. All plots are empty.
2. A house is placed on one side of the street.
3. A house is placed on the other side of the street.
4. Two houses are placed, one on each side of the street.
Example 2:

Input: n = 2
Output: 9
Explanation: The 9 possible arrangements are shown in the diagram above.
Constraints:
1 <= n <= 10^4
Solution
Approach: Dynamic Programming
The two sides of the street are independent, so count the ways for one side and square the result. For one side let f[i] be the number of ways for the first i + 1 plots when plot i has a house, and g[i] when it does not. A house at plot i forces no house at i - 1, so f[i] = g[i-1]. No house at i leaves plot i - 1 free, so g[i] = f[i-1] + g[i-1]. Start from f[0] = g[0] = 1. The answer is (f[n-1] + g[n-1])^2 modulo 10^9 + 7.
Complexity: Time O(n), space O(n).
class Solution:
def countHousePlacements(self, n: int) -> int:
mod = 10**9 + 7
f = [1] * n
g = [1] * n
for i in range(1, n):
f[i] = g[i - 1]
g[i] = (f[i - 1] + g[i - 1]) % mod
v = f[-1] + g[-1]
return v * v % mod