Approach
Sorting and greedy selection
For Filter Occupied Intervals, 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 Python from the credited upstream file filter-occupied-intervals.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.
123 45class Solution(object):6 def filterOccupiedIntervals(self, occupiedIntervals, freeStart, freeEnd):7 """8 :type occupiedIntervals: List[List[int]]9 :type freeStart: int10 :type freeEnd: int11 :rtype: List[List[int]]12 """13 def merged_intervals(intervals):14 intervals.sort(key=lambda x: x[0])15 merged = []16 for l, r in intervals:17 if not merged or merged[-1][1]+1 < l:18 merged.append([l, r])19 else:20 merged[-1][1] = max(merged[-1][1], r) 21 return merged22 23 def overlapped(a, b):24 return max(a[0], b[0]) <= min(a[1], b[1])25 26 result = []27 for x in merged_intervals(occupiedIntervals):28 if not overlapped(x, [freeStart, freeEnd]):29 result.append(x)30 continue31 if x[0] <= freeStart-1:32 result.append([x[0], freeStart-1])33 if freeEnd+1 <= x[1]:34 result.append([freeEnd+1, x[1]])35 return result36