Approach
Sorting and greedy selection
For Minimize Connected Groups by Inserting Interval, 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
- 27 lines of Python from the credited upstream file 3323.py.
- The implementation visibly relies on sequence storage.
- No explicit 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 def minConnectedGroups(self, intervals: list[list[int]], k: int) -> int:3 mergedIntervals = 04 maxMergedIntervals = 05 6 intervals = self._merge(intervals)7 8 i = 09 for _, end in intervals:10 while i < len(intervals) and end + k >= intervals[i][0]:11 mergedIntervals += 112 i += 113 mergedIntervals -= 1 14 maxMergedIntervals = max(maxMergedIntervals, mergedIntervals)15 16 return len(intervals) - maxMergedIntervals17 18 19 def _merge(self, intervals: list[list[int]]) -> list[list[int]]:20 res = []21 for interval in sorted(intervals):22 if not res or res[-1][1] < interval[0]:23 res.append(interval)24 else:25 res[-1][1] = max(res[-1][1], interval[1])26 return res27