Merge Overlapping Intervals in DSA Typescript - Time & Space Complexity
We want to understand how the time needed to merge overlapping intervals changes as the number of intervals grows.
How does the program's work increase when we add more intervals?
Analyze the time complexity of the following code snippet.
function mergeIntervals(intervals: number[][]): number[][] {
intervals.sort((a, b) => a[0] - b[0]);
const merged: number[][] = [];
for (const interval of intervals) {
if (!merged.length || merged[merged.length - 1][1] < interval[0]) {
merged.push(interval);
} else {
merged[merged.length - 1][1] = Math.max(merged[merged.length - 1][1], interval[1]);
}
}
return merged;
}
This code sorts intervals by start time, then merges any that overlap into one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Sorting the intervals array.
- How many times: Sorting takes multiple comparisons, roughly proportional to n log n where n is the number of intervals.
- Secondary operation: One loop through all intervals to merge them, running n times.
As the number of intervals grows, sorting takes more time, growing faster than just going through the list once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 * log(10) ≈ 33 operations for sorting + 10 for merging |
| 100 | About 100 * log(100) ≈ 664 operations for sorting + 100 for merging |
| 1000 | About 1000 * log(1000) ≈ 9966 operations for sorting + 1000 for merging |
Pattern observation: The sorting step dominates and grows faster than the merging loop as input size increases.
Time Complexity: O(n log n)
This means the time needed grows a bit faster than the number of intervals because of sorting, but merging is just a simple pass through.
[X] Wrong: "Merging intervals takes only O(n) time because we just loop once."
[OK] Correct: While merging is O(n), the sorting step before merging takes more time, 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 removes overlaps by creating a single interval covering all overlapping parts.Final Answer:
To combine intervals that overlap into a single continuous interval -> Option DQuick Check:
Merging = Combine overlaps [OK]
- Thinking merging sorts intervals only
- Confusing merging with removing duplicates
- Believing merging splits intervals
Solution
Step 1: Identify sorting by start time
Sorting by start time means comparing the first element of each interval (a[0] and b[0]).Step 2: Check correct comparison function
Subtracting a[0] - b[0] sorts ascending by start time, which is correct.Final Answer:
intervals.sort((a, b) => a[0] - b[0]); -> Option AQuick Check:
Sort by start = a[0] - b[0] [OK]
- Sorting by end time instead of start time
- Adding values instead of subtracting in sort
- Using wrong indices for comparison
function mergeIntervals(intervals: number[][]): number[][] {
intervals.sort((a, b) => a[0] - b[0]);
const merged: number[][] = [];
for (const interval of intervals) {
if (!merged.length || merged[merged.length - 1][1] < interval[0]) {
merged.push(interval);
} else {
merged[merged.length - 1][1] = Math.max(merged[merged.length - 1][1], interval[1]);
}
}
return merged;
}
console.log(mergeIntervals([[1,3],[2,6],[8,10],[15,18]]));Solution
Step 1: Sort intervals by start
Sorted intervals: [[1,3],[2,6],[8,10],[15,18]] (already sorted)Step 2: Merge overlapping intervals
First interval [1,3] added.
Second interval [2,6] overlaps with [1,3], merge to [1,6].
Third interval [8,10] no overlap, add.
Fourth interval [15,18] no overlap, add.Final Answer:
[[1,6],[8,10],[15,18]] -> Option CQuick Check:
Merged intervals = [[1,6],[8,10],[15,18]] [OK]
- Not sorting intervals before merging
- Overwriting intervals incorrectly
- Missing to merge overlapping intervals
function merge(intervals: number[][]): number[][] {
intervals.sort((a, b) => a[0] - b[0]);
const result: number[][] = [];
for (let i = 0; i < intervals.length; i++) {
if (result.length === 0 || result[result.length - 1][1] <= intervals[i][0]) {
result.push(intervals[i]);
} else {
result[result.length - 1][1] = Math.max(result[result.length - 1][1], intervals[i][1]);
}
}
return result;
}Solution
Step 1: Analyze overlap condition
Condition uses '<=' which treats touching intervals as non-overlapping.Step 2: Correct overlap detection
Correct condition uses '<' so that when last_end == current_start (touching), it merges since the if condition fails and goes to else. Current '<=' incorrectly pushes new for touching intervals.Final Answer:
The condition should use '<' instead of '<=' to detect overlap -> Option BQuick Check:
Overlap check needs '<' not '<=' [OK]
- Using '<=' causes missing merges on touching intervals
- Ignoring sorting requirement
- Not checking empty input but that is not the bug here
Choose the best approach.
Solution
Step 1: Track counts during merging
When merging intervals, keep a count for each merged interval starting at 1.Step 2: Increment count on overlap
Each time an interval merges into the last merged interval, increment its count to reflect how many intervals combined.Final Answer:
Keep a count alongside each merged interval and increment it when merging overlaps -> Option AQuick Check:
Count merges while merging intervals [OK]
- Sorting by end time does not help counting merges
- Counting after merging loses interval mapping
- Counting total merges instead of per merged interval
Ready to prove it?
Pass the test and this pattern moves unknown
