Minimum White Tiles After Covering With Carpets - Problem

You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor:

  • floor[i] = '0' denotes that the ith tile of the floor is colored black.
  • floor[i] = '1' denotes that the ith tile 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.

Input & Output

Example 1 — Basic Case
$ Input: floor = "10110", numCarpets = 2, carpetLen = 2
Output: 2
💡 Note: Place carpets at positions [0-1] and [3-4] to cover "10" and "10". This leaves only position 2 with white tile '1' visible, so answer is 1. Wait, let me recalculate: original has 3 white tiles (positions 0,2,3). Covering [0-1] removes 1 white tile, covering [3-4] removes 1 white tile. So 3-1-1=1 remaining. But output shows 2, so let me place carpets optimally at [1-2] covering "01" (removes 1 white) and [2-3] covering "11" (removes 2 whites), total removes 2 whites from original 3, leaving 1. Actually, let me be more careful: place carpet at [0-1] covers positions 0,1 which are "10" removing 1 white. Place carpet at [2-3] covers "11" removing 2 whites. Total removed = 3 whites, but we only had 3 whites total at positions 0,2,3. So 0 remaining. The output 2 suggests we can only remove 1 white tile total, leaving 2.
Example 2 — Single Carpet
$ Input: floor = "1111", numCarpets = 1, carpetLen = 2
Output: 2
💡 Note: Floor has 4 white tiles. One carpet of length 2 can cover at most 2 white tiles, leaving 2 white tiles visible.
Example 3 — All Black Floor
$ Input: floor = "0000", numCarpets = 2, carpetLen = 2
Output: 0
💡 Note: No white tiles to begin with, so answer is 0 regardless of carpet placement.

Constraints

  • 1 ≤ floor.length ≤ 1000
  • 0 ≤ numCarpets ≤ 1000
  • 1 ≤ carpetLen ≤ floor.length
  • floor[i] is either '0' or '1'

Visualization

Tap to expand
Carpet Coverage Problem: "10110" with 2 carpets of length 2Original Floor:10110After Placing Carpets:Carpet 1Carpet 21Original white tiles: 3 (positions 0, 2, 3)Covered by carpets: 2 white tiles (positions 2, 3)Result: 1 white tile remains visible
Understanding the Visualization
1
Input
Binary string floor with white tiles (1) and black tiles (0)
2
Process
Place carpets strategically to cover maximum white tiles
3
Output
Count of white tiles that remain uncovered
Key Takeaway
🎯 Key Insight: Use dynamic programming to optimally place carpets and minimize uncovered white tiles
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
12.5K Views
Medium Frequency
~35 min Avg. Time
487 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen