- 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
Check if any interval completely overlaps the other in Python
Suppose, we are given a set of intervals that consists of values (a,b) where a represents the starting time and b represents the ending time of an event. Our task is to check whether any of these intervals completely overlap any other interval in this set. If any of the intervals overlap, we return the result as True, otherwise we return False.
So, if the input is like [(4,6), (10,12), (7,9), (13,16)], then the output will be False. If the input is like [(4,6), (4,9), (7,11), (5,8)], then the output will be True.
To solve this, we will follow these steps −
- sort the list intervals
- for i in range 1 to size of intervals, do
- if intervals[i, 1] <= intervals[i- 1, 1], then
- return True
- return False
- if intervals[i, 1] <= intervals[i- 1, 1], then
Let us see the following implementation to get better understanding −
Example
def solve(intervals): intervals.sort() for i in range(1, len(intervals)): if intervals[i][1] <= intervals[i- 1][1]: return True return False intervals = [(4,6),(10,12),(7,9),(13,16)] intervals2 = [(4,6), (4,9), (7,11), (5,8)] print(solve(intervals)) print(solve(intervals2))
Input
[(4,6),(10,12),(7,9),(13,16)] [(4,6), (4,9), (7,11), (5,8)]
Output
False True
Advertisements