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 Points INPUT x y 1 1 2 3 4 (2,1) (1,1) (4,1) points = [[2,1],[1,1],[4,1]] w = 2 3 points on a plane Rectangle width limit: 2 ALGORITHM STEPS 1 Sort by X Sort points: [1,1],[2,1],[4,1] 2 Start Rect 1 x1=1, covers x in [1,3] 3 Check Points (1,1) OK, (2,1) OK 4 New Rect Needed (4,1) outside, start Rect 2 Rect 1 x: 1-3 Rect 2 x: 4-6 Greedy: extend until can't FINAL RESULT 1-3 4+ Output: 2 rectangles All 3 points covered with minimum rects Key Insight: Sorting points by x-coordinate allows greedy selection. Start a new rectangle at leftmost uncovered point, extend it by width w, and mark all covered points. Repeat until all points are covered. Time Complexity: O(n log n) for sorting. This greedy approach guarantees optimal solution. TutorialsPoint - Minimum Rectangles to Cover Points | Greedy Approach - Sort and Cover
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