
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
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]]
Advertisements