Problem · Array

Insert Interval

Learn this problem
MediumApple logoAppleFULLTIMEPHONE SCREEN

Problem statement

You are given a list of non-overlapping closed intervals intervals, sorted by start time, and one closed interval newInterval.

Insert newInterval so that the result remains sorted and contains no overlapping intervals. Merge every interval that overlaps the inserted interval, and return the resulting list.

Function

insertInterval(intervals: int[][], newInterval: int[]) → int[][]

Examples

Example 1

intervals = [[1,3],[6,9]]newInterval = [2,5]return = [[1,5],[6,9]]

The inserted interval overlaps [1,3], so they merge into [1,5].

Example 2

intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]]newInterval = [4,8]return = [[1,2],[3,10],[12,16]]

The new interval overlaps [3,5], [6,7], and [8,10], producing [3,10].

Constraints

  • 0 <= intervals.length <= 10^4
  • Each interval has exactly two integers [start, end] with start <= end.
  • intervals is sorted by start time and contains no overlapping intervals.
  • newInterval has exactly two integers with newInterval[0] <= newInterval[1].
  • Every endpoint is in [-10^9, 10^9].

More Apple problems

drafts saved locally
public int[][] insertInterval(int[][] intervals, int[] newInterval) {
    // Write your code here.
}
intervals[[1,3],[6,9]]
newInterval[2,5]
expected[[1,5],[6,9]]
checking account