Insert Interval into Sorted List in DSA Python - Time & Space Complexity
We want to understand how the time needed to insert a new interval into a sorted list of intervals changes as the list grows.
Specifically, how does the number of steps grow when we add one interval to many sorted intervals?
Analyze the time complexity of the following code snippet.
def insert_interval(intervals, new_interval):
result = []
i = 0
n = len(intervals)
while i < n and intervals[i][1] < new_interval[0]:
result.append(intervals[i])
i += 1
while i < n and intervals[i][0] <= new_interval[1]:
new_interval[0] = min(new_interval[0], intervals[i][0])
new_interval[1] = max(new_interval[1], intervals[i][1])
i += 1
result.append(new_interval)
while i < n:
result.append(intervals[i])
i += 1
return result
This code inserts a new interval into a sorted list of intervals, merging overlapping intervals.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Three while loops that each traverse parts of the intervals list.
- How many times: Each loop moves forward through the list without going back, together covering all intervals once.
As the number of intervals grows, the code checks each interval at most once to find where to insert and merge.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and merges |
| 100 | About 100 checks and merges |
| 1000 | About 1000 checks and merges |
Pattern observation: The number of operations grows roughly in direct proportion to the number of intervals.
Time Complexity: O(n)
This means the time to insert grows linearly with the number of intervals in the list.
[X] Wrong: "Since the list is sorted, we can insert the interval in constant time without checking all intervals."
[OK] Correct: Even though the list is sorted, we must check intervals to find overlaps and merge them, which requires looking at many intervals in the worst case.
Understanding this linear time complexity helps you explain how to efficiently handle interval merging, a common problem in coding interviews and real-world scheduling tasks.
"What if the intervals list was not sorted? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem requirement
The goal is to insert a new interval into a sorted list of intervals without overlaps.Step 2: Merge overlapping intervals after insertion
After inserting, merge any intervals that overlap to maintain the sorted, non-overlapping property.Final Answer:
To add the new interval and merge any overlapping intervals to keep the list sorted and non-overlapping -> Option AQuick Check:
Insert and merge intervals = To add the new interval and merge any overlapping intervals to keep the list sorted and non-overlapping [OK]
- Ignoring merging after insertion
- Inserting without maintaining order
- Replacing intervals incorrectly
Solution
Step 1: Identify correct insertion method
Using insert(index, element) places the new interval at the correct position without losing order.Step 2: Understand other options
append adds at end without order, sort only sorts but doesn't insert, remove deletes an element.Final Answer:
intervals.insert(2, new_interval) -> Option DQuick Check:
Use insert() to add at specific position [OK]
- Using append without sorting
- Using remove instead of insert
- Relying on sort without insertion
intervals = [[1,3],[6,9]]
new_interval = [2,5]
# Insert new_interval and merge
result = []
i = 0
while i < len(intervals) and intervals[i][1] < new_interval[0]:
result.append(intervals[i])
i += 1
while i < len(intervals) and intervals[i][0] <= new_interval[1]:
new_interval[0] = min(new_interval[0], intervals[i][0])
new_interval[1] = max(new_interval[1], intervals[i][1])
i += 1
result.append(new_interval)
while i < len(intervals):
result.append(intervals[i])
i += 1
print(result)Solution
Step 1: Add intervals before new_interval
The first while loop checks if intervals[i][1] < new_interval[0]. For i=0, 3 < 2 is false, so no intervals added before. result = [].Step 2: Merge overlapping intervals
Intervals overlapping with new_interval [2,5] are [1,3] and [2,5] merged to [1,5].Step 3: Add remaining intervals
Remaining interval [6,9] is added after merged interval.Final Answer:
[[1, 5], [6, 9]] -> Option CQuick Check:
Merged intervals = [[1, 5], [6, 9]] [OK]
- Not merging overlapping intervals
- Appending new_interval without merging
- Incorrect loop conditions
def insert_interval(intervals, new_interval):
result = []
for interval in intervals:
if interval[1] < new_interval[0]:
result.append(interval)
elif interval[0] > new_interval[1]:
result.append(new_interval)
else:
new_interval[0] = min(new_interval[0], interval[0])
new_interval[1] = max(new_interval[1], interval[1])
result.append(new_interval)
return result
print(insert_interval([[1,3],[6,9]], [2,5]))Solution
Step 1: Analyze loop behavior
Appending new_interval inside the loop when interval[0] > new_interval[1] causes multiple appends.Step 2: Understand consequences
This leads to duplicates and incorrect order in the result list.Final Answer:
Appending new_interval inside loop causes duplicates -> Option AQuick Check:
Append new_interval once after loop [OK]
- Appending inside loop multiple times
- Not merging intervals properly
- Confusing interval boundaries
[[1,2],[3,5],[6,7],[8,10],[12,16]] and a new interval [4,8], what is the final list after inserting and merging?Solution
Step 1: Identify intervals overlapping with [4,8]
Intervals [3,5], [6,7], and [8,10] overlap with [4,8].Step 2: Merge overlapping intervals
Merge [3,5], [6,7], [8,10], and [4,8] into [3,10].Step 3: Combine with non-overlapping intervals
Keep [1,2] and [12,16] as is, final list is [[1,2],[3,10],[12,16]].Final Answer:
[[1,2],[3,10],[12,16]] -> Option BQuick Check:
Merged intervals = [[1,2],[3,10],[12,16]] [OK]
- Not merging all overlapping intervals
- Appending new interval without merging
- Incorrectly splitting intervals
Ready to prove it?
Pass the test and this pattern moves unknown
