
- 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
Find Intersecting Intervals in Python
Suppose we have a list of intervals, where each interval is like [start, end] this is representing start and end times of an intervals (inclusive), We have to find their intersection, i.e. the interval that lies within all of the given intervals.
So, if the input is like [[10, 110],[20, 60],[25, 75]], then the output will be [25, 60]
To solve this, we will follow these steps −
- start, end := interval after deleting last element from intervals list
- while intervals is not empty, do
- start_temp, end_temp := interval after deleting last element from intervals list
- start := maximum of start, start_temp
- end := minimum of end, end_temp
- return an interval [start, end]
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, intervals): start, end = intervals.pop() while intervals: start_temp, end_temp = intervals.pop() start = max(start, start_temp) end = min(end, end_temp) return [start, end] ob = Solution() intervals = [[10, 110],[20, 60],[25, 75]] print(ob.solve(intervals))
Input
[[10, 110],[20, 60],[25, 75]]
Output
[25, 60]
- Related Articles
- Program to count number of intervals which are intersecting at given point in Python
- Merge Intervals in Python
- Program to find intervals by merging target interval in Python
- Program to find partition array into disjoint intervals in Python
- Program to find contiguous intervals of a unique array in Python
- Program to find smallest intersecting element of each row in a matrix in Python
- Program to find overlapping intervals and return them in ascending order in Python
- Program to find intervals that do not intersect the cut interval in Python
- Program to find total unique duration from a list of intervals in Python
- Find Intersection of all Intervals in C++
- Program to count number of intervals that is totally contained inside other intervals in Python
- Program to find length of longest interval from a list of intervals in Python
- Python Pandas - Check if the Intervals in the IntervalArray is empty
- Python Pandas - Check if the IntervalIndex has overlapping intervals
- Program to merge intervals and sort them in ascending order in Python

Advertisements