![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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]
Advertisements