Insert Interval
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Given sorted non-overlapping intervals and a new interval, insert it and merge if needed.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1Which intervals end before the new one starts?
- Hint 2Which intervals start before the new one ends (and are not in the first group)?
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
A timetable already neatly in order, and a new meeting wants a slot. Copy everything that ends before the new meeting begins. Everything that touches the new meeting gets swallowed into one longer meeting. Then copy everything that starts after it ends.
- The obvious way
Append and run the whole merge-intervals routine: O(n log n).
- The key insight
Walk through once. Phase 1: while an interval ends before the new start, copy it. Phase 2: while an interval starts at or before the new end, grow the new interval to cover it (min of starts, max of ends); then add the grown interval. Phase 3: copy the rest. O(n) with no sorting.
- The algorithm
- Copy intervals whose end is smaller than the new start.
- While an interval's start <= new end, merge it into the new interval.
- Add the merged new interval.
- Copy all remaining intervals.
Watch it run
Exampleintervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], new = [4,8]
1-2 ends at 2, before 4 starts: copy it.
result: 1-2
Where people slip
- Add the merged interval after the second loop, once, not inside it.
- Touching counts as overlap: the conditions use < and <= exactly like this.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def insert(intervals, new_interval):
result = []
position = 0
count = len(intervals)
while position < count and intervals[position][1] < new_interval[0]:
result.append(intervals[position]) # clearly before the new one
position += 1
while position < count and intervals[position][0] <= new_interval[1]:
new_interval = [min(new_interval[0], intervals[position][0]),
max(new_interval[1], intervals[position][1])] # swallow what touches it
position += 1
result.append(new_interval)
result.extend(intervals[position:]) # clearly after the new one
return resultNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.