
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
In many programming problems, Intervals are used to represent ranges such as time periods, numeric spans, etc. An interval is typically represented as a pair of numbers (start, end) where start<=end.
Checking Interval Overlaps Completely in Python
In this article, we are going to learn how to check if any interval completely overlaps with the other in Python. i.e. checking if an interval x= (a1, a2) fully contains the other interval Y= (b1, b2) which occurs when a1<=b1 and a2>b2.
The following are the example scenarios:
Scenario 1
Input: [(1, 5), (2, 4), (6, 7)] Output: True Explanation: The interval (1,5) overlaps completely with the interval (2,4) because 1<=2 and 5>=4. Which indicates that the entire range of (2,4) lies within the (1,5), so the function returns true.
Scenario 2
Input: [(1, 3), (4, 6), (7, 9)] Output: False Explanation: The intervals here are non-overlapping and do not contains each other. No interval in the given input starts before and ends after another.
Example 1
Let's look at the following example, where we are going to consider the input [(1, 5), (2, 4), (6, 7)] and check whether it completely overlaps or not.
def demo(x): n = len(x) for i in range(n): for j in range(n): if i != j: a_start, a_end = x[i] b_start, b_end = x[j] if a_start <= b_start and a_end >= b_end: return True return False x = [(1, 5), (2, 3), (6, 8)] print(demo(x))
Following is the output of the above program:
True
Example 2
Consider the following example, where we are going to check whether if any interval in the list [(1, 3), (4, 6), (7, 9)] completely overlaps or not.
def demo(x): n = len(x) for i in range(n): for j in range(n): if i != j: a_start, a_end = x[i] b_start, b_end = x[j] if a_start <= b_start and a_end >= b_end: return True return False x = [(1, 3), (4, 6), (7, 9)] print(demo(x))
If we run the above program, it will generate the following output:
False
Conclusion
Checking if one interval overlaps completely with another is a useful technique in many real-world applications, like scheduling, resource allocation. In this article, we implemented a straightforward solution using nested loops.