- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Program to find overlapping intervals and return them in ascending order in Python
Suppose we have a list of closed intervals and another list of intervals. Individually, each list is non-overlapping and they are sorted in non-decreasing order. We have to find the overlap of the two intervals sorted in non-decreasing order.
So, if the input is like inv1 = [[50, 100],[190, 270],[310, 330]] inv2 = [[40, 120],[180, 190]], then the output will be [[50, 100], [190, 190]]
To solve this, we will follow these steps −
- ans := a new list
- i := 0, j := 0
- while i < size of A and j < size of B, do
- if start <= end, then
- insert interval [start, end] into ans
- if A[i, 1] < B[j, 1], then
- i := i + 1
- otherwise,
- j := j + 1
- if start <= end, then
- return ans
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, A, B): ans = [] i = 0 j = 0 while i < len(A) and j < len(B): start = max(A[i][0], B[j][0]) end = min(A[i][1], B[j][1]) if start <= end: ans.append([start, end]) if A[i][1] < B[j][1]: i += 1 else: j += 1 return ans ob = Solution() inv1 = [[50, 100],[190, 270],[310, 330]] inv2 = [[40, 120],[180, 190]] print(ob.solve(inv1, inv2))
Input
[[50, 100],[190, 270],[310, 330]], [[40, 120],[180, 190]]
Output
[[50, 100], [190, 190]]
- Related Articles
- Program to merge intervals and sort them in ascending order in Python
- Program to find k sublists with largest sums and return sums in ascending order in Python
- Non-overlapping Intervals in C++
- Program to find the minimum cost to arrange the numbers in ascending or descending order in Python
- Python program to sort out words of the sentence in ascending order
- Program to sort a given linked list into ascending order in python
- Python program to sort the elements of an array in ascending order
- Merge Overlapping Intervals using C++.
- Python Pandas - Check if the IntervalIndex has overlapping intervals
- 8085 Program to perform bubble sort in ascending order
- 8085 Program to perform selection sort in ascending order
- Is it possible to divide records in both ascending and descending order in MySQL and display them alternatively?
- Program to find maximum number of non-overlapping substrings in Python
- Sort index in ascending order – Python Pandas
- Program to find intervals by merging target interval in Python

Advertisements