Approach
Sorting and greedy selection
For Check if Grid can be Cut into Sections, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 36 lines of Java from the credited upstream file 3394.java.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public boolean checkValidCuts(int n, int[][] rectangles) {3 int[][] xs = new int[rectangles.length][2];4 int[][] ys = new int[rectangles.length][2];5 6 for (int i = 0; i < rectangles.length; ++i) {7 xs[i][0] = rectangles[i][0];8 xs[i][1] = rectangles[i][2];9 ys[i][0] = rectangles[i][1];10 ys[i][1] = rectangles[i][3];11 }12 13 return Math.max(countMerged(xs), countMerged(ys)) >= 3;14 }15 16 private int countMerged(int[][] intervals) {17 int count = 0;18 int prevEnd = 0;19 20 Arrays.sort(intervals, Comparator.comparingInt((int[] interval) -> interval[0]));21 22 for (int[] interval : intervals) {23 final int start = interval[0];24 final int end = interval[1];25 if (start < prevEnd) {26 prevEnd = Math.max(prevEnd, end);27 } else {28 prevEnd = end;29 ++count;30 }31 }32 33 return count;34 }35}36