Merge Overlapping Intervals in DSA Python - Time & Space Complexity
We want to understand how the time needed to merge overlapping intervals changes as the number of intervals grows.
Specifically, how does the work increase when we have more intervals to merge?
Analyze the time complexity of the following code snippet.
def merge_intervals(intervals):
intervals.sort(key=lambda x: x[0])
merged = []
for interval in intervals:
if not merged or merged[-1][1] < interval[0]:
merged.append(interval)
else:
merged[-1][1] = max(merged[-1][1], interval[1])
return merged
This code sorts intervals by start time and then merges any that overlap into one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Sorting the list of intervals and then looping through each interval once.
- How many times: Sorting takes multiple comparisons depending on number of intervals (n), and the loop runs once for each interval (n times).
Sorting grows faster than just looping, so it dominates the time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 log 10 ≈ 33 operations |
| 100 | About 100 log 100 ≈ 664 operations |
| 1000 | About 1000 log 1000 ≈ 9966 operations |
Pattern observation: As input size grows, operations grow a bit more than linearly because of sorting.
Time Complexity: O(n log n)
This means the time grows a bit faster than the number of intervals because sorting takes extra work, then merging is quick.
[X] Wrong: "Merging intervals takes only O(n) time because we just loop once."
[OK] Correct: Sorting the intervals first takes more time than just looping, so the total time is dominated by sorting, not just the loop.
Understanding this time complexity helps you explain why sorting is important before merging and shows you can analyze combined steps clearly.
"What if the intervals were already sorted? How would the time complexity change?"
Practice
Solution
Step 1: Understand overlapping intervals
Overlapping intervals share some common range, so merging combines them into one continuous interval.Step 2: Purpose of merging
Merging reduces multiple overlapping intervals into fewer intervals without overlaps.Final Answer:
To combine intervals that overlap into a single continuous interval -> Option CQuick Check:
Merging = Combining overlaps [OK]
- Thinking merging means sorting only
- Confusing merging with removing duplicates
- Assuming intervals are split instead of combined
Solution
Step 1: Identify sorting key for intervals
We sort intervals by their start time, which is the first element in each interval.Step 2: Check code correctness
Using intervals.sort(key=lambda x: x[0]) sorts by start time ascending, which is correct.Final Answer:
intervals.sort(key=lambda x: x[0]) -> Option BQuick Check:
Sort by start time = key x[0] [OK]
- Sorting by end time instead of start time
- Using sorted(intervals) which returns new list without modifying original
- Sorting in reverse order before merging
intervals = [[1,3],[2,6],[8,10],[15,18]]
intervals.sort(key=lambda x: x[0])
merged = []
for interval in intervals:
if not merged or merged[-1][1] < interval[0]:
merged.append(interval)
else:
merged[-1][1] = max(merged[-1][1], interval[1])
print(merged)Solution
Step 1: Sort intervals by start time
Intervals after sorting: [[1,3],[2,6],[8,10],[15,18]] (already sorted)Step 2: Merge overlapping intervals
First interval [1,3] added. Next [2,6] overlaps with [1,3], merged to [1,6]. Then [8,10] no overlap, added. Finally [15,18] no overlap, added.Final Answer:
[[1, 6], [8, 10], [15, 18]] -> Option AQuick Check:
Merged intervals = [[1,6],[8,10],[15,18]] [OK]
- Not updating the end of merged interval
- Appending intervals without merging
- Incorrectly sorting intervals
def merge_intervals(intervals):
intervals.sort()
merged = []
for i in range(len(intervals)):
if not merged or merged[-1][1] < intervals[i][0]:
merged.append(intervals[i])
else:
merged[-1][1] = max(merged[-1][1], intervals[i][1])
return merged
print(merge_intervals([(1,4),(2,3)]))Solution
Step 1: Identify data type of intervals elements
Intervals are list of tuples like [(1,4),(2,3)], tuples are immutable.Step 2: Trace the merging process
After sorting, append first tuple (1,4) to merged. Second overlaps, attempt merged[-1][1] = max(4,3) fails: 'tuple' object does not support item assignment.Final Answer:
Modifying merged[-1][1] directly causes an error because tuples are immutable -> Option DQuick Check:
Tuples immutable, can't modify [OK]
- Assuming all intervals are lists when they might be tuples
- Ignoring immutability errors
- Thinking sorting always needs a key
Solution
Step 1: Sort intervals by start time
Sorting ensures intervals are processed in order, e.g. [[1,10],[2,5],[6,9],[11,15]].Step 2: Merge by extending end to max of overlapping intervals
When intervals overlap or are nested, update the end of merged interval to the maximum end value.Step 3: Result
Merged intervals become [[1,10],[11,15]] because [2,5] and [6,9] are inside [1,10].Final Answer:
Sort intervals by start time and merge by extending the end to max of overlapping intervals -> Option AQuick Check:
Sort + max end merge = correct nested handling [OK]
- Sorting by end time instead of start time
- Removing nested intervals instead of merging
- Merging only exact matches, missing nested cases
Ready to prove it?
Pass the test and this pattern moves unknown
