November 11, 2024
Now I'm onto intervals. This one merges all intersecting intervals and returns the distinct items.
1class Solution:2 def merge(self, intervals: List[List[int]]) -> List[List[int]]:3 res = []4 intervals = sorted(intervals)5 start, end = intervals[0]6 for item in intervals[1:]:7 if end >= item[0] and item[1] > end:8 end = item[1]9 if start >= item[0] and start <= item[1]:10 start = item[0]11 if end < item[0] or start > item[1]:12 res.append([start, end])13 start, end = item14 res.append([start, end])15 return res
O(n) = nlog(n) due to the sorted() method
LeetCode 49. Group Anagrams
LeetCode 57. Insert Interval