#3394

Check if Grid can be Cut into Sections

Medium
ArraySortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach focuses on identifying the unique cut positions and checking if we can create three sections with at least one rectangle in each section. This is done in a single pass for both horizontal and vertical cuts, making it much more efficient.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create sets for unique horizontal and vertical cut positions from the rectangle coordinates.
  2. 2Step 2: Sort the unique cut positions.
  3. 3Step 3: Use a single pass to count rectangles in each section for both horizontal and vertical cuts.
  4. 4Step 4: Check if there exists a pair of cuts that divides the rectangles into three sections with at least one rectangle in each.
solution.py19 lines
1def can_cut_grid(n, rectangles):
2    horizontal_cuts = sorted(set(y2 for _, y1, _, y2 in rectangles))
3    vertical_cuts = sorted(set(x2 for x1, _, x2, _ in rectangles))
4    return check_cuts(rectangles, horizontal_cuts, True) or check_cuts(rectangles, vertical_cuts, False)
5
6def check_cuts(rectangles, cuts, is_horizontal):
7    for i in range(len(cuts) - 1):
8        sections = [0, 0, 0]
9        for x1, y1, x2, y2 in rectangles:
10            if is_horizontal:
11                if y2 <= cuts[i]: sections[0] += 1
12                elif y1 >= cuts[i + 1]: sections[2] += 1
13                else: sections[1] += 1
14            else:
15                if x2 <= cuts[i]: sections[0] += 1
16                elif x1 >= cuts[i + 1]: sections[2] += 1
17                else: sections[1] += 1
18        if all(s > 0 for s in sections): return True
19    return False

Complexity note: The time complexity is O(n) because we only pass through the rectangles a limited number of times, and the space complexity is O(n) due to storing unique cut positions.

  • 1Understanding how to identify unique cut positions is crucial for optimizing the solution.
  • 2Using sets to store cut positions helps in avoiding duplicates and simplifies the logic.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.