You are given a list of ‘N’ non-overlapping intervals (each interval can be represented using two integers ‘start’ and ‘end’), sorted in ascending order (based on ‘start’ values). Your task is to insert a given interval in the list, such that all the intervals are present in sorted order.
In case the given interval overlaps with other intervals, merge all necessary intervals to produce a list containing only non-overlapping intervals.
Example:
Let’s say the list of intervals is: [[1,3], [5,7], [8,12]] and we need to insert the interval [4,6] into the list. [4,6] must be inserted in the second position. After insertion, since [4,6] overlaps with [5,7], we merge them into one interval [4,7]. So, our resulting list is: [[1,3], [4,7], [8,12]]
The first line of input contains an integer ‘T’ representing the number of test cases.
The first of every test case contains the positive integer ‘N’ denoting the number of intervals present in the list.
Next ‘N’ lines contain two space-separated integers, ‘start’ and ‘end’, denoting the starting and the ending point of the interval present in the list.
The next line contains two space-separated integers, start and end, denoting the starting and the ending point of the interval which is to be inserted into the list.
Output Format:
For each test case, return the list after inserting the given interval.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 5 * 10^4
1 <= start <= end <= 10^5
Time Limit: 1 sec
2
3
1 3
5 7
8 12
4 6
2
2 3
5 8
1 9
1 3
4 7
8 12
1 9
For the first test case, The list of intervals is: [[1,3], [5,7], [8,12]] and we need to insert the interval [4,6] into the list. [4,6] must be inserted in the second position. After insertion, since [4,6] overlaps with [5,7], we merge them into one interval [4,7]. So, our resulting list is: [[1,3], [4,7], [8,12]]
For the second test case, N = 2. The list of intervals is: [[2,3], [5,8]] and we need to insert the interval [1,9] into the list. [4,6] must be inserted in the first position. After insertion, since it overlaps with [2,3] and [5,8], we merge them into one interval [1,9]. So, our resulting list is: [[1,9]].
2
3
1 3
5 7
8 12
4 10
2
2 3
5 10
1 4
1 3
4 12
1 4
5 10
Can you solve this problem using stack?
O(N), where ‘N’ is the length of the list.
We are iterating over the complete list of intervals, which will take O(N) time. Hence, the overall complexity is O(N).
O(N), where ‘N’ is the length of the list.
O(N) extra space is required for the stack. We are also making an array to store the intervals after inserting the given interval. Thus, overall space complexity is O(N + N) = O(N).