Insert Interval

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]]
Input Format:
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.
Constraints:
1 <= T <= 10 
1 <= N <= 5 * 10^4
1 <= start <= end <= 10^5

Time Limit: 1 sec
CodingNinjas
author
2y

I didn't have any experience with Python, so I didn't know how to write the syntax.
Step 1: One can do this by using the slice indexing in the list

CodingNinjas
author
2y
Using Stack
  • A simple approach to solve this problem is by using a stack.
  • The idea is to one by one insert the intervals into the stack. At each step, we merge the required intervals and make sure that t...read more
CodingNinjas
author
2y
Traversing and Merging
  • The previous approach required extra space for the stack. We can avoid this by performing the merge operation in-place.
  • The idea is to first put all the intervals less than the gi...read more
Add answer anonymously...
S&P Global Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter