imashutosh51

Insert Interval

May 16th, 2026
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.95 KB | None | 0 0
  1. '''
  2. First append the newer elements at right position as intervals array is already sorted and then apply the merge intervals
  3. '''
  4.  
  5. def merge(arr):
  6.         ans=[]
  7.         prev_start=arr[0][0]
  8.         prev_end=arr[0][1]
  9.         for i in arr:
  10.             cur_start=i[0]
  11.             cur_end=i[1]
  12.             if cur_start<=prev_end:
  13.                 prev_end=max(cur_end,prev_end)
  14.             else:
  15.                 ans.append([prev_start,prev_end])
  16.                 prev_start=cur_start
  17.                 prev_end=cur_end
  18.         ans.append([prev_start,prev_end])
  19.         return ans
  20.  
  21. class Solution:
  22.     def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
  23.         for i in range(len(intervals)):
  24.             if newInterval[0] < intervals[i][0]:
  25.                 intervals.insert(i,newInterval)
  26.                 break
  27.         else:
  28.             intervals.append(newInterval)
  29.         return merge(intervals)
  30.        
Advertisement
Add Comment
Please, Sign In to add comment