|
| 1 | +''' |
| 2 | +# 435. Non-overlapping Intervals |
| 3 | +
|
| 4 | +## understanding the problem |
| 5 | +- 겹치지 않는 인터벌을 최대한 많이 남기기 위해, 지워야하는 인터벌의 최소값 반환 |
| 6 | +- not it: 그래프에 순환이 있는지 여부를 알아본다❌ overkill |
| 7 | +- core approach: Greedy |
| 8 | +
|
| 9 | +## Greedy |
| 10 | +- Whenever you detect an overlap, you should remove one. |
| 11 | + - not physically. we'll going to return counts, so just keep counts is enough. |
| 12 | +- Goal: keep many non-overlapping intervals as possible to minimize removal. |
| 13 | +
|
| 14 | +### how to detect overlap? |
| 15 | +1. sort intervals by ends |
| 16 | +2. iterate through intervals while tracking down the prev_end(last vaild end time) |
| 17 | + - if `current_start < prev_end`, it's overlap. |
| 18 | + - Example: |
| 19 | + - [2, 4] is overlap with [1, 3] |
| 20 | + - start (2) is smaller than end (3) |
| 21 | +
|
| 22 | +### which one should removed? |
| 23 | +- when overlap happens, remove the interval that ends later |
| 24 | + - it will restrict more future intervals. |
| 25 | + - the longer an interval lasts, the more it blocks others(leaving less room for non-overlapping intervals) |
| 26 | +
|
| 27 | +## complexity |
| 28 | +
|
| 29 | +### TC is O(n log n) |
| 30 | +- sorting: O(n log n) |
| 31 | +- iterating: O(n) |
| 32 | +- total: O(n log n) |
| 33 | +
|
| 34 | +### SC is O(1) |
| 35 | +- no extra space is used |
| 36 | +''' |
| 37 | +class Solution: |
| 38 | + def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: |
| 39 | + intervals.sort(key=lambda x: x[1]) |
| 40 | + |
| 41 | + count = 0 # number of removals |
| 42 | + prev_end = intervals[0][1] # last valid end time |
| 43 | + |
| 44 | + for start, end in intervals[1:]: # 1 ~ n-1 |
| 45 | + if start < prev_end: # overlap detected |
| 46 | + count += 1 |
| 47 | + # <do NOT move the prev_end pointer> |
| 48 | + # prev_end is still pointing at the previous interval |
| 49 | + # so it's keeping the interval ends earlier. (removing the longer one) |
| 50 | + else: |
| 51 | + prev_end = end |
| 52 | + |
| 53 | + return count |
0 commit comments