Check if Grid can be Cut into Sections - Problem
Grid Cutting Challenge: You're working with an n ร— n grid where rectangles are placed strategically. Your mission is to determine if you can make exactly two cuts (either both horizontal OR both vertical) to divide the grid into three sections, where each section contains at least one rectangle.

๐ŸŽฏ The Goal: Given rectangle coordinates in the format [startX, startY, endX, endY], check if it's possible to create three distinct sections using two parallel cuts.

๐Ÿ“ Coordinate System: The grid uses a bottom-left origin, meaning (0, 0) is at the bottom-left corner. Each rectangle is defined by its bottom-left corner (startX, startY) and top-right corner (endX, endY).

Return true if such cuts are possible, false otherwise.

Input & Output

example_1.py โ€” Basic Case
$ Input: n = 4, rectangles = [[0,0,2,1], [2,2,3,4], [0,3,1,4]]
โ€บ Output: true
๐Ÿ’ก Note: Two horizontal cuts at y=1 and y=2 create three sections: bottom section has rectangle [0,0,2,1], middle section is empty but we can adjust cuts, and top section has rectangles [2,2,3,4] and [0,3,1,4]. We can make horizontal cuts at y=1.5 and y=2.5 to create valid sections.
example_2.py โ€” Vertical Cuts
$ Input: n = 5, rectangles = [[0,1,1,3], [2,0,4,2], [4,3,5,5]]
โ€บ Output: true
๐Ÿ’ก Note: Two vertical cuts at x=1.5 and x=3.5 create three sections: left section contains [0,1,1,3], middle section contains [2,0,4,2], and right section contains [4,3,5,5].
example_3.py โ€” No Valid Cuts
$ Input: n = 3, rectangles = [[0,0,3,1], [0,2,3,3]]
โ€บ Output: false
๐Ÿ’ก Note: Both rectangles span the full width, so no vertical cuts can separate them. For horizontal cuts, we'd need one cut to separate sections, but we need exactly two cuts to create three sections, and there's no way to create a valid middle section.

Constraints

  • 3 โ‰ค n โ‰ค 104
  • 3 โ‰ค rectangles.length โ‰ค 105
  • rectangles[i].length == 4
  • 0 โ‰ค startx < endx โ‰ค n
  • 0 โ‰ค starty < endy โ‰ค n
  • All rectangles are distinct and do not overlap

Visualization

Tap to expand
Cut 1Cut 2Grid Cutting SolutionSection 1 โœ“Section 2 โœ“Section 3 โœ“
Understanding the Visualization
1
Analyze Layout
Study the placement of all rectangles on the grid
2
Identify Boundaries
Mark all significant coordinate boundaries where cuts could be effective
3
Test Cut Pairs
Systematically test pairs of cut positions to find valid solutions
4
Validate Sections
Ensure each resulting section contains at least one rectangle
Key Takeaway
๐ŸŽฏ Key Insight: Optimal cuts occur at rectangle boundaries, reducing search space dramatically and enabling efficient solutions.
Asked in
Google 45 Amazon 32 Meta 28 Microsoft 25
23.4K Views
Medium Frequency
~25 min Avg. Time
847 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