imashutosh51

Merge Intervals

Feb 4th, 2026
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | None | 0 0
  1. """
  2. Intuition:
  3. To merge intervals, first sort them by start time so overlapping intervals become adjacent.
  4. Then keep a running "current interval" (prev_start, prev_end). For each next interval:
  5. - If its start is greater than prev_end, there is no overlap, so push the current interval to output
  6.  and start a new one.
  7. - Otherwise, it overlaps, so extend prev_end = max(prev_end, end).
  8. Finally, append the last tracked interval. Sorting dominates the time complexity: O(n log n).
  9. """
  10. class Solution:
  11.     def merge(self, arr: List[List[int]]) -> List[List[int]]:
  12.         arr.sort()
  13.         prev_open=arr[0][0]
  14.         prev_close=arr[0][1]
  15.         ans=[]
  16.         for i in range(1,len(arr)):
  17.             if arr[i][0]>prev_close:
  18.                 ans.append([prev_open,prev_close])
  19.                 prev_open,prev_close=arr[i][0],arr[i][1]
  20.             else:
  21.                 prev_close=max(arr[i][1],prev_close) #for overlapping intervals, update the closing value
  22.         ans.append([prev_open,prev_close])
  23.         return ans
Advertisement
Add Comment
Please, Sign In to add comment