- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- 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

# 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 < 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

## 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 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))

## Input

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

## Output

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

- 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
- 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 partition array into disjoint intervals in Python
- Find Intersecting Intervals in Python
- Python program to print sorted number formed by merging all elements in array
- Program to find shortest cycle length holding target 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 minimum interval to include each query 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 combinations of coins to reach target in Python