Merge Intervals in Python



Suppose we have a collection of intervals, we have to merge all overlapping intervals. So if the intervals are like [[1,3], [2,6], [8,10], [15,18]], then the intervals after merging will be [[1,6],[8,10],[15,18]]. This is because there were two intervals those are overlapping, the intervals are [1,3] and [2,6], these are merged to [1,6]

Let us see the steps −

  • if interval list length is 0, then return a blank list
  • sort the interval list using quicksort mechanism
  • stack := an empty stack, and insert intervals[0] into the stack
  • for i in range 1 to length of intervals – 1
    • last_element := top element of stack
    • if end of last_element >= first element of intervals[i], then
      • end of last_element = max of end of intervals[i], and end of last_element
      • pop element from stack
      • push last_element into stack
    • else push intervals[i] into stack
  • return stack

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution(object):    def merge(self, intervals):       """       :type intervals: List[Interval]       :rtype: List[Interval]       """       if len(intervals) == 0:          return []       self.quicksort(intervals,0,len(intervals)-1)       #for i in intervals:          #print(i.start, i.end)       stack = []       stack.append(intervals[0])       for i in range(1,len(intervals)):          last_element= stack[len(stack)-1]          if last_element[1] >= intervals[i][0]:             last_element[1] = max(intervals[i][1],last_element[1])             stack.pop(len(stack)-1)             stack.append(last_element)          else:             stack.append(intervals[i])       return stack    def partition(self,array,start,end):       pivot_index = start       for i in range(start,end):          if array[i][0]<=array[end][0]:             array[i],array[pivot_index] =array[pivot_index],array[i]             pivot_index+=1       array[end],array[pivot_index] =array[pivot_index],array[end]       return pivot_index    def quicksort(self,array,start,end):       if start<end:          partition_index = self.partition(array,start,end)          self.quicksort(array,start,partition_index-1)          self.quicksort(array, partition_index + 1, end) ob1 = Solution() print(ob1.merge([[1,3],[2,6],[8,10],[15,18]]))

Input

[[1,3],[2,6],[8,10],[15,18]]

Output

[[1, 6], [8, 10], [15, 18]]
Updated on: 2020-05-04T05:55:55+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements