Menu
CoddyTech

Insert Interval

MediumIntervalspython iconjava iconcpp iconc iconjs icon+10

You get intervals sorted by start as two arrays: interval i is [starts[i], ends[i]], and no two overlap or touch. Insert the new interval [newStart, newEnd], merge it with every interval it overlaps or touches, and return all intervals as [start, end] pairs sorted by start.

Intervals touch when one ends where the other starts, as [2, 4] and [4, 8] do, and touching intervals merge. [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.
challenge icon

Follow-up

If you insert many intervals one after another, how would you store them so each insert costs O(log n) plus one step per old interval it swallows?

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

Test #1

Test #2

Test #3

Arguments

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

Expected Output

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