Problem
You are given an integer n
representing the dimensions of an n x n
grid, with the origin at the bottom-left corner of the grid. You are also given a 2D array of coordinates rectangles
, where rectangles[i]
is in the form [startx, starty, endx, endy]
, representing a rectangle on the grid. Each rectangle is defined as follows:
(startx, starty)
: The bottom-left corner of the rectangle.(endx, endy)
: The top-right corner of the rectangle.
Note that the rectangles do not overlap. Your task is to determine if it is possible to make either two horizontal or two vertical cuts on the grid such that:
- Each of the three resulting sections formed by the cuts contains at least one rectangle.
- Every rectangle belongs to exactly one section.
Return true
if such cuts can be made; otherwise, return false
.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Solution
Method 1 - Sorting
-
Extract Intervals:
- The rectangles represent intervals on either the x-axis (horizontal intervals) or y-axis (vertical intervals).
- We extract these intervals (
x_bounds
for the x-axis andy_bounds
for the y-axis) to handle the problem separately for horizontal and vertical cuts.
-
Sort Intervals:
- The intervals are sorted based on their starting coordinates (
interval[0]
). This helps us in efficiently determining sections.
- The intervals are sorted based on their starting coordinates (
-
Count Sections:
- After sorting, iterate through the intervals to check where a new section starts. A new section begins when the current interval starts after the maximum boundary of the previous intervals.
- For each section, update the
max_boundary
to track the farthest end of the current section.
-
Validation:
- If at least two sections are formed (
section_count >= 2
), it implies valid cuts are possible to divide the rectangles correctly, and we returnTrue
.
- If at least two sections are formed (
-
Final Result:
- The method checks both x-axis and y-axis cuts independently to determine validity. If either axis has valid cuts, the result is
True
.
- The method checks both x-axis and y-axis cuts independently to determine validity. If either axis has valid cuts, the result is
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m log m)
- Interval extraction:
O(m)
(wherem
is the number of rectangles). - Sorting intervals:
O(m log m)
. - Iterating intervals to check sections:
O(m)
. - Overall:
O(m log m)
, dominated by sorting.
- Interval extraction:
- 🧺 Space complexity:
O(m)
- Space for extracting intervals (
x_bounds
andy_bounds
):O(m)
. - Space for sorting intermediate structures:
O(m)
. - Overall:
O(m)
, proportional to the number of rectangles.
- Space for extracting intervals (