#2209
Minimum White Tiles After Covering With Carpets
HardStringDynamic ProgrammingPrefix SumDynamic ProgrammingPrefix Sum
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * numCarpets) |
| Space | O(1) | O(n * numCarpets) |
💡
Intuition
Time O(n * numCarpets)Space O(n * numCarpets)
The optimal solution uses dynamic programming to efficiently calculate the minimum number of visible white tiles. By breaking the problem down into smaller subproblems, we can build up the solution without redundant calculations.
⚙️
Algorithm
3 steps- 1Step 1: Create a DP array where DP[i][j] represents the minimum number of visible white tiles from index i to the end using j carpets.
- 2Step 2: Iterate through the DP array, filling in values based on previous calculations and the effect of placing carpets.
- 3Step 3: Use prefix sums to quickly calculate the number of white tiles covered by carpets.
solution.py24 lines
1# Full working Python code
2
3def minWhiteTiles(floor, numCarpets, carpetLen):
4 n = len(floor)
5 dp = [[float('inf')] * (numCarpets + 1) for _ in range(n + 1)]
6 prefixSum = [0] * (n + 1)
7
8 for i in range(n):
9 prefixSum[i + 1] = prefixSum[i] + (1 if floor[i] == '1' else 0)
10
11 for j in range(numCarpets + 1):
12 dp[n][j] = 0
13
14 for i in range(n - 1, -1, -1):
15 for j in range(numCarpets + 1):
16 dp[i][j] = dp[i + 1][j] # Not using a carpet
17 if j > 0:
18 end = min(i + carpetLen, n)
19 dp[i][j] = min(dp[i][j], prefixSum[end] - prefixSum[i] + dp[end][j - 1])
20
21 return dp[0][numCarpets]
22
23# Example usage
24print(minWhiteTiles('10110101', 2, 2))ℹ
Complexity note: This complexity arises because we are filling a DP table of size n by numCarpets, iterating through each tile and each carpet count.
- 1Using dynamic programming allows us to avoid redundant calculations and efficiently compute results.
- 2Prefix sums help in quickly calculating the number of white tiles in a given range.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.