Skip to main content
Back to problems
#3111
Medium Algorithms

Minimum rectangles to cover points

Array Greedy Sorting
63.6% acceptance
Feb 23, 2026
109
8
You are given a 2D integer array points, where points[i] = [xi, yi]. You are also given an integer w. Your task is to cover all the given points with rectangles. Each rectangle has its lower end at some point (x1, 0) and its upper end at some point (x2, y2), where x1 <= x2, y2 >= 0, and the condition x2 - x1 <= w must be satisfied for each rectangle. A point is considered covered by a rectangle if it lies within or on the boundary of the rectangle. Return an integer denoting the minimum number of rectangles needed so that each point is covered by at least one rectangle. Note: A point may be covered by more than one rectangle.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_rectangles_to_cover_points(points: Vec<Vec<i32>>, w: i32) -> i32 {
    let mut xs: Vec<i32> = points.iter().map(|p| p[0]).collect();
    xs.sort_unstable();
    xs.dedup();

    let mut count = 0;
    let mut i = 0;
    while i < xs.len() {
      let start = xs[i];
      count += 1;
      // Skip all points within [start, start + w]
      while i < xs.len() && xs[i] <= start + w {
        i += 1;
      }
    }
    count
  }
}