Check if Grid can be Cut into Sections - Problem

You are given an integer n representing the dimensions of an n × 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 [start_x, start_y, end_x, end_y], representing a rectangle on the grid.

Each rectangle is defined as follows:

  • (start_x, start_y): The bottom-left corner of the rectangle.
  • (end_x, end_y): 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.

Input & Output

Example 1 — Valid Horizontal Cuts
$ Input: n = 5, rectangles = [[0,0,3,3],[0,3,3,5],[3,0,5,5]]
Output: true
💡 Note: We can make horizontal cuts at y=3 and y=4. This creates three sections: bottom (y≤3) contains rectangles [0,0,3,3] and [3,0,5,5], middle (3
Example 2 — No Valid Cuts
$ Input: n = 4, rectangles = [[0,0,1,1],[2,2,3,3]]
Output: false
💡 Note: Only two rectangles exist in opposite corners. Any two cuts will create three sections, but the middle section will always be empty since rectangles don't span the middle area.
Example 3 — Valid Vertical Cuts
$ Input: n = 6, rectangles = [[0,0,2,6],[2,0,4,6],[4,0,6,6]]
Output: true
💡 Note: We can make vertical cuts at x=2 and x=4. This creates three sections: left (x≤2) contains [0,0,2,6], middle (24) contains [4,0,6,6].

Constraints

  • 3 ≤ n ≤ 109
  • 3 ≤ rectangles.length ≤ 105
  • rectangles[i].length == 4
  • 0 ≤ startx < endx ≤ n
  • 0 ≤ starty < endy ≤ n
  • All rectangles are mutually disjoint

Visualization

Tap to expand
Grid Cutting Problem: Create Three Valid SectionsInput: Grid with RectanglesCut 1Cut 2Two Horizontal CutsSection 1: ✓Section 2: ✓Section 3: ✓Result: true (each section has ≥1 rectangle)
Understanding the Visualization
1
Input Grid
n×n grid with non-overlapping rectangles positioned by coordinates
2
Find Cuts
Identify two parallel cuts (horizontal or vertical) that create 3 sections
3
Validate
Each section must contain at least one complete rectangle
Key Takeaway
🎯 Key Insight: Valid cuts must align with rectangle boundaries to cleanly separate them into exactly three non-empty sections
Asked in
Google 15 Meta 12 Amazon 8
18.5K Views
Medium Frequency
~25 min Avg. Time
890 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