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 −


 Live Demo

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]]


[[10, 110],[20, 60],[25, 75]]


[25, 60]

Updated on: 23-Sep-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started