Menu
CoddyTech

Insert Interval

MediumIntervalspython iconjava iconcpp iconc iconjs icon+10

You get a list of intervals sorted by start, given as two arrays of the same length: interval i is [starts[i], ends[i]]. No two of them overlap or touch. You also get one new interval, [newStart, newEnd]. Insert it, merge it with every interval it overlaps or touches, and return all the intervals as a 2D array of [start, end] pairs, sorted by start.

Two intervals touch when one ends where the other starts, as [2, 4] and [4, 8] do, and touching intervals merge into one. [1, 2] and [3, 4] share no point, so they stay apart.

Function

insertInterval(starts: integer-array, ends: integer-array, newStart: integer, newEnd: integer) → integer-2d-array
startsinteger-array
the start of each interval, in increasing order
endsinteger-array
the end of each interval, matching starts
newStartinteger
the start of the interval to insert
newEndinteger
the end of the interval to insert
Returnsinteger-2d-array
the intervals after the insert as [start, end] pairs, sorted by start

Constraints

  • 1 ≤ starts.length == ends.length ≤ 2000
  • 0 ≤ starts[i] ≤ ends[i] ≤ 105
  • ends[i] < starts[i+1]: the intervals are sorted by start, and no two of them overlap or touch.
  • 0 ≤ newStart ≤ newEnd ≤ 105

Examples

Input
starts = [1, 5, 10, 15]ends = [3, 7, 12, 18]newStart = 6newEnd = 11
Output
[[1, 3], [5, 12], [15, 18]]
Explanation
[6, 11] overlaps [5, 7] and [10, 12], so the three become [5, 12]. [1, 3] ends before 6 and [15, 18] starts after 12, so both stay as they are.

lock icon+20 hidden tests on Submit

challenge icon

Follow-up

Suppose you insert many new intervals, one after another, into the same list. How would you store the intervals so that each insert costs O(log n) plus one step for every old interval it swallows?

Reset code
def insertInterval(starts, ends, newStart, newEnd):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

starts = [1, 5, 10, 15]
ends = [3, 7, 12, 18]
newStart = 6
newEnd = 11

Expected

[[1, 3], [5, 12], [15, 18]]