
- 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
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
- Related Articles
- Check elementwise if an Interval overlaps the values in the IntervalArray in Python Pandas
- Python Pandas - Check elementwise if an Interval overlaps the values in the IntervalArray created from an array of splits
- How to check if a given directory contains any other directory in Python?
- Python Pandas - Check if an interval is empty
- Program to check two rectangular overlaps or not in Python
- Python Pandas - Check if the Pandas Index holds Interval objects
- Python Pandas - Check if the interval is open on the left side
- Python Pandas - Check if the interval is open on the right side
- Python Pandas - Check if an element belongs to an Interval
- Python Pandas - Check if an interval is empty if closed from the left side
- Python Pandas - Check if an interval is empty if closed from the both sides
- Python Pandas - Check if an Interval is closed on the left side
- Python Pandas - Check if an Interval is closed on the right side
- Check if tuple has any None value in Python
- Python Pandas - Check if an interval set as open is empty

Advertisements