Intermediate · medium · array, intervals
Insert Interval
The challenge
You are given a list of non-overlapping intervals [start, end], sorted by start, and one new interval. Insert the new interval so that the list stays sorted and without overlaps, merging it with every interval it touches.
Example
[[1, 3], [6, 9]] + [2, 5]
-> [[1, 5], [6, 9]]
[[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]] + [4, 8]
-> [[1, 2], [3, 10], [12, 16]]Idea: the list is already sorted, so there is no need to sort it again: it splits into three parts. First, copy the intervals that end before the new one starts. Then merge every interval that starts before the new one ends, keeping the smaller start and the larger end. Finally, add the merged interval and copy the rest as they are. One pass: time O(n), plus O(n) for the output list.
The solution
# Insert Interval - ayotl.dev
def insert(ivs, new):
s, e = new
out, i, n = [], 0, len(ivs)
# 1) the ones that end before it
while i < n and ivs[i][1] < s:
out.append(ivs[i])
i += 1
# 2) the ones that overlap: merge
while i < n and ivs[i][0] <= e:
s = min(s, ivs[i][0])
e = max(e, ivs[i][1])
i += 1
out.append([s, e])
# 3) the rest, as they are
return out + ivs[i:]
print(insert([[1, 3], [6, 9]], [2, 5]))
print(insert([[1, 2], [3, 5], [6, 7],
[8, 10], [12, 16]], [4, 8]))
$ python3 insert_interval.py
[[1, 5], [6, 9]]
[[1, 2], [3, 10], [12, 16]]