
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- if s > end, then
- ans := ans + end - start + 1
- return ans
Let us see the following implementation to get better understanding −
Example
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
- Related Articles
- Program to find contiguous intervals of a unique array in Python
- Program to find length of longest interval from a list of intervals in Python
- Program to find total duration of K most watched shows in Python
- Python Program to print unique values from a list
- Program to find number of unique people from list of contact mail ids in Python
- Python Program to get all unique keys from a List of Dictionaries
- Program to find total number of strings, that contains one unique characters in Python
- Program to find the number of unique integers in a sorted list in Python
- Python Program to Find the Total Sum of a Nested List Using Recursion
- Program to find three unique elements from list whose sum is closest to k Python
- Get unique values from a list in Python
- C# program to print unique values from a list
- Java program to print unique values from a list
- Program to find minimum total cost for equalizing list elements in Python
- Program to find folded list from a given linked list in Python

Advertisements