Minimum White Tiles After Covering With Carpets Problem
#2209
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2209.
You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor:
floor[i] = '0'denotes that thei^thtile of the floor is colored black.- On the other hand,
floor[i] = '1'denotes that thei^thtile of the floor is colored white.
You are also given numCarpets and carpetLen. You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum. Carpets may overlap one another.
Return the minimum number of white tiles still visible.
Example 1:

Input: floor = "10110101", numCarpets = 2, carpetLen = 2
Output: 2
Explanation:
The figure above shows one way of covering the tiles with the carpets such that only 2 white tiles are visible.
No other way of covering the tiles with the carpets can leave less than 2 white tiles visible.
Example 2:

Input: floor = "11111", numCarpets = 2, carpetLen = 3
Output: 0
Explanation:
The figure above shows one way of covering the tiles with the carpets such that no white tiles are visible.
Note that the carpets are able to overlap one another.
Constraints:
1 <= carpetLen <= floor.length <= 1000floor[i]is either'0'or'1'.1 <= numCarpets <= 1000
Solution
Approach: Memoized search
Let dfs(i, j) be the fewest white tiles left uncovered in floor[i..] when j carpets are still available. The answer is dfs(0, numCarpets). Build a prefix sum s of white tiles so that tiles remaining from i on can be read in O(1).
- If
i >= n, nothing is left: return0. - If
j == 0, no carpets remain: returns[n] - s[i]. - If
floor[i]is black, skip it:dfs(i + 1, j). - Otherwise choose the better of leaving this white tile uncovered,
1 + dfs(i + 1, j), or starting a carpet here,dfs(i + carpetLen, j - 1).
Memoize on (i, j).
Complexity: O(n * numCarpets) time and space.
from functools import lru_cache
class Solution:
def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:
@lru_cache(None)
def dfs(i: int, j: int) -> int:
if i >= n:
return 0
if floor[i] == "0":
return dfs(i + 1, j)
if j == 0:
return s[-1] - s[i]
return min(1 + dfs(i + 1, j), dfs(i + carpetLen, j - 1))
n = len(floor)
s = [0] * (n + 1)
for i, c in enumerate(floor):
s[i + 1] = s[i] + int(c == "1")
ans = dfs(0, numCarpets)
dfs.cache_clear()
return ans