- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

- if s <= union[end], then
- return best

Let us see the following implementation to get better understanding −

## Example

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

- Related Questions & Answers
- Program to find length of longest Fibonacci subsequence from a given list in Python
- Program to find length of longest alternating subsequence from a given list in Python
- Program to find length of longest sign alternating subsequence from a list of numbers in Python
- Program to find length of longest arithmetic subsequence of a given list in Python
- Program to find total unique duration from a list of intervals in Python
- Program to find length of longest matrix path length in Python
- Program to find length of longest possible stick in Python?
- Program to find length of longest balanced subsequence in Python
- Program to find length of longest anagram subsequence in Python
- Program to find length of longest consecutive sequence in Python
- Program to find length of longest distinct sublist in Python
- Program to find length of longest increasing subsequence in Python
- Program to find length of longest palindromic substring in Python
- Program to find length of longest palindromic subsequence in Python
- Program to find length of longest fibonacci subsequence in Python

Advertisements