Paint House — LeetCode 256 Python Solution

MediumLeetCode PremiumArrayDynamic Programming
Problem
#256
Reading time
2 min

The problem

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.

Example

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.

Python solution

Python
class Solution:
    def minCost(self, costs: List[List[int]]) -> int:
        a = b = c = 0
        for ca, cb, cc in costs:
            a, b, c = min(b, c) + ca, min(a, c) + cb, min(a, b) + cc
        return min(a, b, c)

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 256. Paint House is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 256. Paint House?
LeetCode 256. Paint House is rated Medium on LeetCode.
What topics does LeetCode 256. Paint House cover?
LeetCode 256. Paint House is tagged Array and Dynamic Programming on LeetCode.
Is LeetCode 256. Paint House a premium problem?
Yes. LeetCode 256. Paint House is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview