- Related Questions & Answers
- Program to find intervals that do not intersect the cut interval in Python
- Program to find length of longest interval from a list of intervals in Python
- Find Intersecting Intervals in Python
- Program to find minimum number colors remain after merging in Python
- Program to find minimum steps to reach target position by a chess knight in Python
- Program to find one minimum possible interval to insert into an interval list in Python
- Program to find contiguous intervals of a unique array in Python
- Program to find shortest cycle length holding target in python
- Program to find minimum distance to the target element using Python
- Program to find overlapping intervals and return them in ascending order in Python
- Program to find total unique duration from a list of intervals in Python
- Program to find number of given operations required to reach Target in Python
- Program to find number of combinations of coins to reach target in Python
- Python Program to Print Numbers in an Interval
- Program to find lowest sum of pairs greater than given target in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 < size of iv, do

if start time of iv[i] <= end time of last interval of res, then

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

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 i < len(iv): if iv[i][0] <= res[-1][1]: res[-1][1] = max(res[-1][1], iv[i][1]) else: res.append(iv[i]) i += 1 return res ob = Solution() intervals = [ [1, 15], [25, 35], [75, 90] ] target = [10, 30] print(ob.solve(intervals, target))

[[1, 15],[25, 35],[75, 90]], [10, 30]

[[1, 35], [75, 90]]

Advertisements