Taro Logo

Paint House

Medium
Asked by:
Google
LinkedIn
Citadel
Uber
199 views
Topics:
Dynamic Programming

There is a row of n houses, where each house can be painted one of three colors: red, blue, or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.

The cost of painting each house with a certain color is represented by an n x 3 cost matrix costs.

  • For example, costs[0][0] is the cost of painting house 0 with the color red; costs[1][2] is the cost of painting house 1 with color green, and so on...

Return the minimum cost to paint all houses.

Example 1:

Input: costs = [[17,2,17],[16,16,5],[14,3,19]]
Output: 10
Explanation: Paint house 0 into blue, paint house 1 into green, paint house 2 into blue.
Minimum cost: 2 + 5 + 3 = 10.

Example 2:

Input: costs = [[7,6,2]]
Output: 2

Constraints:

  • costs.length == n
  • costs[i].length == 3
  • 1 <= n <= 100
  • 1 <= costs[i][j] <= 100

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 structure and dimension of the `costs` array? Is it guaranteed to be an $n imes 3$ matrix?
  2. Can the cost values in the array be negative, zero, or only positive integers?
  3. How should we handle an empty input array (`n = 0`)? Should it return a cost of 0?
  4. Are we allowed to modify the input `costs` array in place to optimize space, or should we treat the input as read-only?
  5. Is the number of available colors strictly limited to three, or could the number of colors vary per house or overall?

Brute Force Solution

Approach

Imagine you have a row of houses and a palette of different paint colors, and you want to paint every house while following the rule that no two neighboring houses can be painted the same color. The brute force approach works by testing every single possible color combination from the first house to the last, calculating the total cost for each complete combination, and finally picking the one that cost the least money.

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

  1. Start at the very first house in the row and imagine painting it with the first available color choice.
  2. Move to the second house and choose a color that is different from the color you just used on the first house.
  3. Continue this process all the way down the line to the final house, making sure at each step that you never paint two adjacent houses the same color.
  4. Once you reach the end of the row with a complete set of colors for every house, add up the total cost of this specific coloring plan and write it down.
  5. Go back and change the color of the last house to a different valid option, and calculate the new total cost.
  6. Systematically explore every single branch of color choices for every single house, just like testing every combination on a combination lock.
  7. After you have explored and calculated the cost for every conceivable way to paint the whole row of houses, look at all your totals and select the plan that resulted in the lowest overall cost.

Code Implementation

def min_cost(costs):
    if not costs:
        return 0

    def calculate_cost(house_index, current_color):
        current_cost = costs[house_index][current_color]
        
        # Base case to stop recursion once we evaluate the final house in our row
        if house_index == len(costs) - 1:
            return current_cost

        minimum_remaining_cost = float('inf')
        
        # Iterate through all available colors to find the optimal valid path forward
        for next_color in range(3):
            if next_color != current_color:
                subsequent_cost = calculate_cost(house_index + 1, next_color)
                if subsequent_cost < minimum_remaining_cost:
                    minimum_remaining_cost = subsequent_cost

        return current_cost + minimum_remaining_cost

    total_minimum_cost = float('inf')
    
    # Test every valid starting color for the first house to initiate our search
    for starting_color in range(3):
        candidate_cost = calculate_cost(0, starting_color)
        if candidate_cost < total_minimum_cost:
            total_minimum_cost = candidate_cost

        # Return the ultimate minimum cost found across all explored branches
    return total_minimum_cost

Big(O) Analysis

Time Complexity
O(3ⁿ) – The input size n represents the total number of houses in the row to be painted. At each house, we branch out and test up to 2 alternative valid colors from our palette, excluding the color used on the immediately preceding house. For a row of n houses, this recursive branch exploration multiplies by 2 at each step, resulting in roughly 3 times 2^(n-1) total operations. When we simplify this exponential combination testing, the overall time complexity evaluates to O(3ⁿ).
Space Complexity
O(1) – The brute force approach described tests every combination by keeping track of only a few scalar variables for the current path and minimum cost, without allocating any extra data structures that grow with the input size. Because no auxiliary arrays, hash maps, or recursive call stacks are utilized to store intermediate results, the memory consumption remains completely constant. Therefore, the extra auxiliary space required is independent of the number of houses N, resulting in an optimal space complexity of O(1).

Optimal Solution

Approach

Instead of testing every possible color combination for every house from the start, we can work our way forward step by step. By keeping track of the cheapest running totals for each color as we move from one house to the next, we guarantee we find the absolute cheapest overall cost without redoing any work.

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

  1. Look at the first house and note down the cost of painting it red, blue, or green.
  2. Move to the second house and figure out the cheapest way to paint it red by adding its painting cost to the cheaper of the two possible choices from the previous house.
  3. Do the same for the other two colors on the second house, making sure no two houses in a row share the same color.
  4. Continue this exact same forward process for every subsequent house, always building upon the best totals calculated from the house immediately before it.
  5. Once you reach the final house, look at the three running totals and pick the smallest one as your final answer.

Code Implementation

def min_cost(costs):
    if not costs:
        return 0

    # We modify the input matrix in place to save memory during traversal.
    for house_index in range(1, len(costs)):

        costs[house_index][0] += min(costs[house_index - 1][1], costs[house_index - 1][2])
        costs[house_index][1] += min(costs[house_index - 1][0], costs[house_index - 1][2])
        costs[house_index][2] += min(costs[house_index - 1][0], costs[house_index - 1][1])

    # The last row now contains total minimum costs for finishing with each color.
    return min(costs[-1])

Big(O) Analysis

Time Complexity
O(n) – The input size is defined by n, which represents the total number of houses to paint. The cost is driven by a single forward pass iterating through each house from the second one to the final one. At each house, we perform a constant number of operations, specifically three additions and comparisons to update the running costs for the three possible colors. Summing this constant amount of work across all n houses results in approximately 3 * n operations, which simplifies to Big O of n.
Space Complexity
O(1) – As we process each house from the first to the final one, we only need to keep track of the running costs for the three colors from the immediately preceding house. Instead of creating an auxiliary array of size N to store the running totals for every single house, we can overwrite or update a few scalar variables or a fixed-size array of three elements. Since these temporary variables do not grow in quantity regardless of how many houses are in the input, the extra memory used remains constant. Thus, the auxiliary space complexity simplifies to Big O of 1.

Edge Cases

Empty or null costs array
How to Handle:
Return zero immediately as no houses need to be painted.
Single house scenario where n equals 1
How to Handle:
Return the minimum cost among the three color options for that single house.
Large input scale with maximum allowed houses
How to Handle:
Iterative dynamic programming ensures linear time complexity and constant auxiliary space without stack overflow.
All costs are identical across houses and colors
How to Handle:
The transition state logic naturally picks the valid non-adjacent minimums to accumulate the total cost.
Extremely skewed cost distributions with very large numbers
How to Handle:
Standard 32-bit or 64-bit integers will not overflow if total costs stay within data type limits.
Zero or negative cost values in the matrix
How to Handle:
Mathematical addition functions correctly with negative values because minimizing sums still holds true.