Program to find total unique duration from a list of intervals in Python


Suppose we have a list of intervals where each list represents an interval [start, end] (inclusive). We have to find the total unique duration it covers.

So, if the input is like intervals = [[2, 11],[13, 31],[41, 61]], then the output will be 50, as the total unique covered distance is (11 - 2 + 1) = 10 then (31 - 13 + 1) = 19 and (61 - 41 + 1) = 21, so total is 50.

To solve this, we will follow these steps −

  • if intervals list is empty, then
    • return 0
  • sort the list intervals
  • [start, end] := intervals[0]
  • ans := 0
  • for each start and end (s, e) in intervals, do
    • if s > end, then
      • ans := ans + end - start + 1
      • start := s, end := e
    • otherwise,
      • end := maximum of end, e
  • ans := ans + end - start + 1
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, intervals):
      if not intervals:
         return 0
         intervals.sort()
         start, end = intervals[0]
         ans = 0
         for s, e in intervals:
            if s > end:
               ans += end - start + 1
               start = s
               end = e
            else:
               end = max(end, e)
            ans += end - start + 1
         return ans
ob = Solution()
intervals = [[2, 11],[13, 31],[41, 61]]
print(ob.solve(intervals))

Input

[[2, 11],[13, 31],[41, 61]]

Output

50

Updated on: 19-Nov-2020

810 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements