Minimum Rectangles to Cover Points - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: points = [[2,1],[1,1],[4,1]], w = 2
Output: 2
💡 Note: We can cover point (1,1) and (2,1) with one rectangle [1,3], and point (4,1) with another rectangle [4,6]. Total: 2 rectangles.
Example 2 — Single Rectangle
$ Input: points = [[1,0],[1,1],[2,0]], w = 2
Output: 1
💡 Note: All points have x-coordinates between 1 and 2, so one rectangle [1,3] can cover all points.
Example 3 — Wide Spread
$ Input: points = [[0,0],[5,0],[10,0]], w = 3
Output: 3
💡 Note: Points are spread far apart. Need rectangle [0,3] for (0,0), [5,8] for (5,0), and [10,13] for (10,0). Total: 3 rectangles.

Constraints

  • 1 ≤ points.length ≤ 1000
  • points[i].length == 2
  • 0 ≤ xi == points[i][0] ≤ 40
  • 0 ≤ yi == points[i][1] ≤ 40
  • 1 ≤ w ≤ 106

Visualization

Tap to expand
Minimum Rectangles to Cover PointsPoints: (2,1), (1,1), (4,1) | Width: w = 2(1,1)(2,1)(4,1)Rectangle 1x ∈ [1, 3]Rectangle 2x ∈ [4, 6]Greedy approach: sort points and place rectangles left to rightResult: 2 rectangles minimum
Understanding the Visualization
1
Input
Points at coordinates (2,1), (1,1), (4,1) with maximum width w=2
2
Process
Sort points and place rectangles greedily from left to right
3
Output
Minimum 2 rectangles needed to cover all points
Key Takeaway
🎯 Key Insight: Sort points by x-coordinate and greedily place rectangles to maximize coverage
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
12.5K Views
Medium Frequency
~15 min Avg. Time
340 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