Insert Interval
LeetCode 57 · Medium · solution, intuition & step-by-step walkthrough
Three phases: before, overlap-merge, after.
This is how I solved Insert Interval (LeetCode 57), a medium problem from the Intervals pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
The intervals are sorted and disjoint. Copy everything that ends before the new interval starts, merge everything that overlaps it into one, then copy the rest.
Approach
- 1
Append intervals ending before newInterval starts.
- 2
While intervals start before newInterval ends, widen newInterval.
- 3
Append the merged interval, then the remainder.
How I solved it
Three-phase sweepPythonO(n) time
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
#1,3 ->new interval 4,5 -> insert - 3<4
#1,3 ->new interval 2,5 -> merge 1<=5 - > start<=new_interval_end
res=[]
i=0
n = len(intervals)
merged = []
#no overlaps before merging
while i<n and intervals[i][1]<newInterval[0]:
merged.append(intervals[i])
i+=1
#intervals after mering
while i<n and intervals[i][0]<=newInterval[1]:
newInterval[0]=min(intervals[i][0],newInterval[0])
newInterval[1]=max(intervals[i][1],newInterval[1])
i+=1
merged.append(newInterval)
#no overlapping intervals after merging
while i<n:
merged.append(intervals[i])
i+=1
return mergedInsert Interval — FAQ
What is the intuition behind Insert Interval?
The intervals are sorted and disjoint. Copy everything that ends before the new interval starts, merge everything that overlaps it into one, then copy the rest.
How do you solve Insert Interval (LeetCode 57)?
1. Append intervals ending before newInterval starts. 2. While intervals start before newInterval ends, widen newInterval. 3. Append the merged interval, then the remainder.
What is the time and space complexity of Insert Interval?
Time: O(n). Space: O(n). (Accepted approach: Three-phase sweep.)
What are common mistakes in Insert Interval?
Touching intervals ([1,2] and [2,3]) overlap.