Advertisement
Iam_Sandeep

435. Non-overlapping Intervals

Jul 26th, 2022
907
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.91 KB | None | 0 0
  1. '''
  2. Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
  3. Input: intervals = [[1,2],[2,3],[3,4],[1,3]]
  4. Output: 1
  5. Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping.
  6. '''
  7. class Solution:
  8.     def eraseOverlapIntervals(self, a: List[List[int]]) -> int:
  9.         '''
  10.        conditions: to remove overlapping ones
  11.        remove the interval which ends late.
  12.        Because we shall be greedy.
  13.        '''
  14.         a.sort(key=lambda x:(x[0],x[1]))
  15.         n=len(a)
  16.         cnt=0
  17.         prev=[-inf,-inf]
  18.         for i in range(n):
  19.             if prev[1]<=a[i][0]:
  20.                 prev=a[i]
  21.                 continue
  22.             else:
  23.                 cnt+=1
  24.                 if prev[1]>a[i][1]:
  25.                     prev=a[i]
  26.         return cnt
  27.            
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement