Program to find length of longest interval from a list of intervals in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of intervals where each interval is in form [start, end]. We have to find the longest interval that we can make by merging any number of overlapping intervals.

So, if the input is like [[1, 6],[4, 9],[5, 6],[11, 14],[16, 20]], then the output will be 9, as after merging, we have the interval [1, 9] of a length 9.

To solve this, we will follow these steps −

  • sort the list intervals
  • union := first interval from the intervals list
  • best := union[end] - union[start] + 1
  • for each start time s and end time e in intervals except the first one, do
    • if s <= union[end], then
      • union[end] := maximum of union[end] and e
    • otherwise,
      • union := a new interval [s, e]
    • best := maximum of best and union[end] - union[start] + 1
  • return best

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, intervals):
      intervals.sort()
      union = intervals[0]
      best = union[1] - union[0] + 1
      for s, e in intervals[1:]:
         if s <= union[1]:
            union[1] = max(union[1], e)
         else:
            union = [s, e]
            best = max(best, union[1] - union[0] + 1)
      return best
ob = Solution()
intervals = [[1, 6],[4, 9],[5, 6],[11, 14],[16, 20]]
print(ob.solve(intervals))

Input

[[1, 6],[4, 9],[5, 6],[11, 14],[16, 20]]

Output

9
raja
Published on 19-Nov-2020 07:15:34
Advertisements