Taro Logo

Count Number of Ways to Place Houses

#1 Most AskedMedium
0 views
Topics:
Dynamic Programming

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 109 + 7.

Note that if a house is placed on the ith plot on one side of the street, a house can also be placed on the ith 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 <= 104

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum value of $n$ we can expect for the number of plots on each side of the street?
  2. Does the problem imply that $n$ can be zero, and if so, how many valid placements are there for zero plots?
  3. Are the two sides of the street completely independent of each other in terms of house placement rules?
  4. Since the result can be very large, should we apply the modulo $10^9 + 7$ operation at each intermediate step or only at the final answer?
  5. Are empty plots (plots with no houses placed on them) considered adjacent, or does adjacency strictly apply only between two houses?

Brute Force Solution

Approach

Imagine you have a street with a certain number of empty spots where you can either build a house or leave the spot empty, with the rule that no two houses can be placed right next to each other. The brute force approach works by exhaustively looking at every single possible combination of placing and skipping houses for the entire street.

Here's how the algorithm would work step-by-step:

  1. Start at the very beginning of the street and consider the first spot.
  2. Decide to either place a house there or leave it empty.
  3. Move to the next spot on the street and make the same choice, but remember that if you placed a house in the previous spot, you are not allowed to place one here.
  4. Continue making these decisions for every single spot all the way to the end of the street.
  5. Once you reach the end, check if your entire sequence of choices followed the rule that no two houses touched each other.
  6. If the sequence is valid, count it as a successful way to place the houses.
  7. Repeat this entire process for every conceivable combination of houses and empty spots from start to finish.
  8. Add up all the successful combinations you found to get your final answer.

Code Implementation

def count_way_to_place_houses(spot_count):
    # We generate every possible binary sequence of length equal to spot count
    all_combinations = [format(sequence_index, f'0{spot_count}b') for sequence_index in range(1 << spot_count)]

    valid_combination_count = 0

    # Iterate through every generated combination to check against adjacency rules
    for combination_string in all_combinations:
        is_valid_sequence = True

        for spot_index in range(spot_count - 1):
            if combination_string[spot_index] == '1' and combination_string[spot_index + 1] == '1':
                is_valid_sequence = False
                break

        # Only configurations where houses are separated by at least one empty spot count
        if is_valid_sequence:
            valid_combination_count += 1

    # Since houses can be placed independently on both sides of the street, square the result
    final_answer = valid_combination_count * valid_combination_count

    return final_answer

Big(O) Analysis

Time Complexity
O(2^n) – The brute force approach exhaustively generates every single possible combination of placing or skipping houses for all n spots on the street. At each of the n spots, the algorithm makes two branching choices to either build a house or leave the spot empty. This recursive decision tree doubles in size with each additional spot, resulting in approximately 2 to the power of n total operations. Simplifying this exponential growth yields a final time complexity of O(2^n).
Space Complexity
O(1) – To solve this problem efficiently based on the described sequential decision-making process, we only need to keep track of the count of valid combinations from the previous one or two spots. By utilizing a few scalar integer variables to store these running counts instead of maintaining an auxiliary array or recursive call stack of size N, the extra memory usage remains entirely constant. As the input size N grows, the number of auxiliary variables does not increase, resulting in a constant auxiliary space complexity.

Optimal Solution

Approach

Instead of checking every single possible combination of placing houses on both sides of the street, we can figure out the solution by looking at just one side of the street first. Because the two sides of the street are completely independent, we simply calculate the number of valid ways for one side and then multiply that result by itself to get the grand total.

Here's how the algorithm would work step-by-step:

  1. Realize that placing houses on one side of the street is exactly the same problem as placing houses on a single straight row, with the golden rule that no two houses can be right next to each other.
  2. Observe that the number of valid ways to place houses on a small row of a specific length builds directly upon the valid ways calculated for the smaller rows that came right before it.
  3. Start by counting the valid ways for a tiny stretch of street, noting that a stretch with zero spots has one way to do nothing, and a stretch with one spot has two ways, which are either placing a house or leaving it empty.
  4. For each next step up in street length, find the total valid arrangements by combining the total valid arrangements from the previous length with the valid arrangements from two lengths ago.
  5. Continue this simple building process step by step until you reach the desired length of the street, giving you the total number of valid ways to build houses safely on one side.
  6. Take that final number of valid ways for one side and multiply it by itself, because every valid arrangement on the left side can be paired with any valid arrangement on the right side.
  7. Celebrate having your final answer instantly without ever needing to list out or check every single house combination manually.

Code Implementation

class Solution:
    def countHousePlacements(self, street_length: int) -> int:
        # Both sides of the street are independent, so we solve for one side first.
        if street_length == 0:
            return 1

        previous_ways = 1
        current_ways = 2

        # Build valid ways iteratively using the Fibonacci pattern constraint.
        for current_length in range(2, street_length + 1):
            next_ways = previous_ways + current_ways
            previous_ways = current_ways
            current_ways = next_ways

        # Multiply combinations from both sides together for the total ways.
        total_one_side = current_ways
        return (total_one_side * total_one_side) % (10**9 + 7)

Big(O) Analysis

Time Complexity
O(n) – To find the number of valid house placements for a street of length n, we iterate through the street lengths from 2 up to n using a single loop. In each iteration, we perform a constant number of basic arithmetic operations to compute the current value based on the previous two stored values. This sequential building process takes operations proportional to n. Finally, multiplying the single-side result by itself takes constant time, meaning the total operations scale linearly and simplify to O(n).
Space Complexity
O(1) – To calculate the valid arrangements for a street of length N, we only need to keep track of the results from the previous two steps rather than storing a full history of all intermediate values. We can achieve this by using just a couple of primitive integer variables to iteratively update our counts as we step up from length 1 to N. Because these few scalar variables require a constant amount of memory that does not grow regardless of how large N becomes, the auxiliary space complexity remains strictly constant.

Edge Cases

Minimum input where n equals 1 plot
How to Handle:
The base case logic correctly computes 2 valid placements per side resulting in 4 total ways.
Maximum allowed input such as n equals 10000
How to Handle:
An iterative dynamic programming approach avoids recursion limit issues and computes the result in linear time.
Large resulting numbers causing integer overflow
How to Handle:
Applying the modulo 10 to the power of 9 plus 7 operation at each step prevents integer overflow.
Independent side calculation requirement
How to Handle:
We compute the valid ways for one side and square the result to account for both sides independently.
Zero or negative values for n
How to Handle:
The problem constraints specify positive integers starting from 1 so invalid ranges are naturally avoided.
0/8 completed