KatInterview

Minimum Paint Strokes to Cover a Board

Greedy & IntervalsAuto-graded · 15 test cases
MediumAuto-gradedGreedy & Intervalsgreedyintervalssorting

Last updated

Tests the ability to merge overlapping intervals greedily to find the fewest horizontal paint strokes needed to fully cover a set of colored segments on a 1-D board.

Minimum Paint Strokes to Cover a Board

You are painting a 1-D board. A paint job is described as a list of segments, where each segment [l, r] means "this region from position l to position r (inclusive) must be painted." Your brush always paints a contiguous stroke: one stroke covers every integer position from some a to some b (inclusive).

Your goal is to find the minimum number of strokes needed so that every required position is covered by at least one stroke. A stroke may legally cover positions that are not required — you just cannot leave any required position uncovered.

Two segments that touch or overlap (i.e., their ranges share at least one integer, or one ends exactly one before the other begins) can always be covered by a single stroke. For example, [1,3] and [4,6] can be covered in one stroke [1,6] because they are adjacent (no gap between 3 and 4).

More precisely, two segments can be merged into one stroke if and only if there is no integer gap between them — that is, left2 <= right1 + 1.

Given a list of segments segments where each element is [l, r] with l <= r, return the minimum number of strokes required to cover all segments.

If segments is empty, return 0.

Constraints

  • 0 <= len(segments) <= 2000
  • Each element of segments is a two-element list [l, r].
  • -10^6 <= l <= r <= 10^6
  • Segments may overlap, be nested, be duplicates, or be given in any order.

Examples

Example 1

Input: min_paint_strokes([[1, 3], [2, 5], [7, 10]])

Output: 2

Example 2

Input: min_paint_strokes([[1, 3], [4, 6], [8, 10]])

Output: 2

Example 3

Input: min_paint_strokes([])

Output: 0

Hints

Hint 1

Sort the segments by their left endpoint first — this lets you process them in order and decide greedily whether a new segment extends the current stroke or starts a fresh one.

Hint 2

After sorting, keep track of the furthest right endpoint reached so far. A new segment can be merged with the current stroke if its left endpoint is at most (current_right + 1).

Hint 3

Remember the adjacency rule: segments [1,3] and [4,6] count as one stroke because there is no integer gap between them. Update your merge condition accordingly.