Program to merge intervals and sort them in ascending order in Python


Suppose we have a list intervals, we have to find the union of them in sorted sequence.

So, if the input is like inv = [[2, 5],[4, 10],[20, 25]], then the output will be [[2, 10], [20, 25]]

To solve this, we will follow these steps −

  • sort the list intervals
  • ans := a new list
  • for each start and end (s, e) in intervals, do
    • if ans and s <= ending time of the last interval of ans, then
      • ending time of the last interval of ans := maximum of e and ending time of the last interval of ans
    • otherwise,
      • insert interval [s, e] into ans
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, intervals):
      intervals.sort()
      ans = []
      for s, e in intervals:
         if ans and s <= ans[-1][1]:
            ans[-1][1] = max(ans[-1][1], e)
         else:
            ans.append([s, e])
      return ans
ob = Solution()
inv = [[2, 5],[4, 10],[20, 25]]
print(ob.solve(inv))

Input

[[2, 5],[4, 10],[20, 25]]

Output

[[2, 10], [20, 25]]

Updated on: 19-Nov-2020

565 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements