#2320
Count Number of Ways to Place Houses
MediumApproaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | Unknown |
| Space | O(1) | Unknown |
💡
Intuition
Time UnknownSpace Unknown
We can use dynamic programming to build the solution incrementally. The number of ways to place houses on one side of the street resembles the Fibonacci sequence, where the current state depends on the previous two states.
⚙️
Algorithm
4 steps- 1Step 1: Define a DP array where dp[i] represents the number of valid arrangements for i plots.
- 2Step 2: Initialize base cases: dp[0] = 1 (no plots) and dp[1] = 2 (either empty or one house).
- 3Step 3: Fill the DP array using the relation dp[i] = dp[i-1] + dp[i-2] for i >= 2.
- 4Step 4: The final answer will be (dp[n] * dp[n]) % (10^9 + 7) since both sides are independent.
solution.py12 lines
1# Full working Python code
2def countWaysOptimal(n):
3 MOD = 10**9 + 7
4 if n == 1:
5 return 4
6 dp = [0] * (n + 1)
7 dp[0], dp[1] = 1, 2
8 for i in range(2, n + 1):
9 dp[i] = (dp[i - 1] + dp[i - 2]) % MOD
10 return (dp[n] * dp[n]) % MOD
11
12print(countWaysOptimal(2))Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.