Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Program to find intervals by merging target interval in Python
Suppose we have a list of non-overlapping intervals. These are sorted based on end time. We have another interval target, find final interval after merging target so that intervals are still non-overlapping and sorted.
So, if the input is like intervals = [[1, 15],[25, 35],[75, 90]], target = [10, 30], then the output will be [[1, 35], [75, 90]] as first two intervals [1, 15] and [25, 35] are merged.
To solve this, we will follow these steps −
insert target at the end of iv
sort iv based on start time
res := a new list with first interval
i := 1
-
while i
-
if start time of iv[i]
end time of last interval of res = maximum of (end time of last interval of res and end time of iv[i])
-
otherwise,
insert iv[i] at the end of res
i := i + 1
-
return res
Example (Python)
Let us see the following implementation to get a better understanding −
class Solution: def solve(self, iv, target): iv.append(target) iv.sort(key=lambda x: x[0]) res = [iv[0]] i = 1 while iInput
[[1, 15],[25, 35],[75, 90]], [10, 30]Output
[[1, 35], [75, 90]]
