I believe this solution is easier to conceptualise so I decided to share.
def insert(intervals, new_interval):
merged = []
start, end = 0, 1
# Set the new interval as our base Interval
start, end = new_interval[start], new_interval[end]
for interval in intervals:
# Our current Interval overlaps the base Interval
if interval[start] <= end and interval[start] >= start:
end = max(interval[end], end)
# Our interval is behind their Interval so we add our v to the merged
# start and end remain the same as they come later
elif interval[start] < start and interval[end] < start:
merged.append(interval)
# The base Interval overlaps our current Interval
# So we need to merged the Intervals
elif interval[start] < start and interval[end] >= start:
start = interval[start]
end = max(interval[end], end)
# Our Interval is ahead of the base Interval so
# we add a new interval with the base Interval values
# and make our current Interval the base Interval values
elif interval[start] > end:
merged.append([start, end])
start, end = interval[start], interval[end]
# Add the last Interval
merged.append([start, end])
return merged
Type your question above this line.
Course: https://www.educative.io/collection/5668639101419520/5671464854355968
Lesson: https://www.educative.io/collection/page/5668639101419520/5671464854355968/5718314357620736