Insert Interval
Understand how to insert a new interval into a sorted list of non-overlapping intervals and merge any overlapping intervals that arise. Explore efficient strategies to maintain sorted order and handle interval overlaps. Practice solving this common interval problem to enhance your coding interview skills.
We'll cover the following...
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
Return the updated list of intervals.
Note: You don’t need to modify
intervalsin place. You can make a new array and return it.
Constraints:
intervals.lengthintervals[i].length,newInterval.lengthstartiendiThe 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
What will be the updated list of intervals?
existing_intervals =
new_interval =
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.
Try it yourself
Implement your solution in the following coding playground.
import java.util.*;class Solution {public static int[][] insertInterval(int[][] existingIntervals, int[] newInterval) {// Replace this placeholder return statement with your codereturn new int[][]{};}}