#3111
Minimum Rectangles to Cover Points
MediumArrayGreedySortingGreedySorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
By sorting the points and using a greedy approach, we can minimize the number of rectangles needed by always extending the rectangle to cover as many points as possible within the width constraint.
⚙️
Algorithm
4 steps- 1Step 1: Sort the points based on their x-coordinates.
- 2Step 2: Initialize a count for rectangles and start from the first point.
- 3Step 3: For each point, create a rectangle that extends to the right until the width exceeds w, covering all points in that range.
- 4Step 4: Move to the next uncovered point and repeat until all points are covered.
solution.py11 lines
1def minRectangles(points, w):
2 points.sort()
3 count = 0
4 i = 0
5 n = len(points)
6 while i < n:
7 count += 1
8 start = points[i][0]
9 while i < n and points[i][0] <= start + w:
10 i += 1
11 return countℹ
Complexity note: The complexity is O(n log n) due to the sorting step, while the greedy selection of rectangles runs in O(n).
- 1The y-values of the points do not affect the rectangle count, only the x-values matter.
- 2Sorting the points allows for a more systematic approach to covering them efficiently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.