There is a street with plots on each side (total plots). You want to place houses such that no two houses are adjacent on the same side of the street. Houses on opposite sides of the street do not affect each other. You need to return the total number of ways to place the houses modulo .
This problem, frequently asked by Microsoft and Amazon, tests your ability to decouple independent events and recognize standard sequences. Since the two sides of the street are independent, the total ways is simply (ways_for_one_side) * (ways_for_one_side). The problem then reduces to finding the number of ways to pick non-adjacent items from a line, which is a classic DP task.
This uses Dynamic Programming, specifically the Fibonacci sequence logic.
dp[i] be the number of ways to place houses in i plots.dp[i-1] ways.i-1, so you have dp[i-2] ways.dp[i] = dp[i-1] + dp[i-2].dp[1]=2 (empty, H) and dp[2]=3 (empty, H-, -H).Let .
One frequent mistake is trying to solve both sides of the street simultaneously in one DP state, which makes the logic much more complicated. Another is missing the fact that the answer should be squared. Some candidates also forget to handle the modulo operation after the multiplication step.
Always check if a problem can be broken down into independent sub-problems. If two parts of a system don't interact (like the two sides of the street), calculate the result for one part and use the multiplication principle of combinatorics.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Ways to Express an Integer as Sum of Powers | Medium | Solve | |
| Domino and Tromino Tiling | Medium | Solve | |
| Knight Dialer | Medium | Solve | |
| Out of Boundary Paths | Medium | Solve | |
| Count Ways To Build Good Strings | Medium | Solve |