...

/

Insert Interval

Insert Interval

Try to solve the Insert Interval problem.

Statement

You are given a list of non-overlapping intervals, intervals, where each interval is represented as [starti, endi] and the list is sorted in ascending order by the start of each interval (starti). You are also given another interval, newInterval = [start, end].

Your task is to insert newInterval into the list of intervals such that the list remains sorted by starting times and still contains no overlapping intervalsOverlapping intervals are two or more intervals with at least one common point in time.. If any intervals overlap after the insertion, merge them accordingly.

Return the updated list of intervals.

Note: You don’t need to modify intervals in place. You can make a new array and return it.

Constraints:

  • 00 \leq intervals.length 104\leq 10^4

  • intervals[i].length, newInterval.length ==2== 2

  • 00 \leq starti << endi 104\leq 10^4

  • The list of intervals is sorted in ascending order based on the start time.

Examples

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps us to check if you’re solving the correct problem:

Insert Interval

1

What will be the updated list of intervals?

existing_intervals = [[1,3],[4,5],[7,8],[9,12],[13,14]][[1, 3], [4, 5], [7, 8], [9, 12], [13, 14]]

new_interval = [2,10][2, 10]

A)

[[1,12],[13,14]][[1, 12], [13, 14]]

B)

[[1,3],[2,10],[4,5],[7,8],[9,12],[13,14]][[1, 3], [2, 10], [4, 5], [7, 8], [9, 12], [13, 14]]

C)

[[2,10],[13,14]][[2, 10], [13, 14]]

Question 1 of 40 attempted

Figure it out

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5
6

Try it yourself

Implement your solution in the following coding playground.

Press + to interact
Java
usercode > Solution.java
import java.util.*;
class Solution {
public static int[][] insertInterval(int[][] existingIntervals, int[] newInterval) {
// Replace this placeholder return statement with your code
return new int[][]{};
}
}
Insert Interval

Access this course and 1200+ top-rated courses and projects.