Merge Overlapping Intervals in DSA C++ - 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 have more intervals to merge?
Analyze the time complexity of the following code snippet.
#include <vector>
#include <algorithm>
using namespace std;
vector<vector<int>> mergeIntervals(vector<vector<int>> &intervals) {
sort(intervals.begin(), intervals.end());
vector<vector<int>> merged;
for (auto &interval : intervals) {
if (merged.empty() || merged.back()[1] < interval[0]) {
merged.push_back(interval);
} else {
merged.back()[1] = max(merged.back()[1], interval[1]);
}
}
return merged;
}
This code sorts intervals and then merges any that overlap into one combined interval.
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 exactly n times.
Sorting grows faster than just looping, so it dominates the time needed.
| 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 faster than just doubling, because sorting costs increase with n log n.
Time Complexity: O(n log n)
This means the time needed grows a little faster than the number of intervals because sorting takes extra work, but merging after sorting is just a simple pass.
[X] Wrong: "The merging loop alone decides the time complexity, so it is O(n)."
[OK] Correct: Sorting the intervals first takes more time than the loop, so the sorting step actually controls the overall time needed.
Understanding how sorting affects the merging process helps you explain your solution clearly and shows you know how to analyze combined steps in algorithms.
"What if the intervals were already sorted? How would the time complexity change?"
Practice
Merge Overlapping Intervals algorithm?Solution
Step 1: Understand the problem goal
The algorithm aims to merge intervals that share common parts so they become one continuous interval.Step 2: Clarify what merging means
Merging means combining overlapping intervals into one that covers the entire range of those intervals.Final Answer:
To combine all intervals that overlap into a single continuous interval -> Option BQuick Check:
Merge overlapping intervals = combine overlaps [OK]
- Confusing merging with sorting
- Thinking it removes intervals instead of combining
- Assuming it finds max length only
Solution
Step 1: Identify sorting by start time
We need to sort intervals by their first element (start time) in ascending order.Step 2: Check lambda comparator correctness
std::sort(intervals.begin(), intervals.end(), [](auto &a, auto &b) { return a[0] < b[0]; }); uses a lambda that compares a[0] < b[0], which sorts ascending by start time correctly.Final Answer:
std::sort(intervals.begin(), intervals.end(), [](auto &a, auto &b) { return a[0] < b[0]; }); -> Option AQuick Check:
Sort by start ascending = a[0] < b[0] [OK]
- Sorting by end time instead of start time
- Sorting in descending order
- Using default sort without comparator on vector of vectors
std::vector intervals = {{1,3},{2,6},{8,10},{15,18}};
// After merging overlapping intervals
// Print merged intervals
for (auto &interval : merged) {
std::cout << "[" << interval[0] << "," << interval[1] << "] ";
}Solution
Step 1: Sort intervals by start time
Sorted intervals: [1,3], [2,6], [8,10], [15,18]Step 2: Merge overlapping intervals
[1,3] and [2,6] overlap, merge to [1,6]. Others remain separate.Final Answer:
[1,6] [8,10] [15,18] -> Option AQuick Check:
Merged intervals = [1,6], [8,10], [15,18] [OK]
- Not merging overlapping intervals
- Printing original intervals without merge
- Merging incorrectly leaving duplicates
std::vector mergeIntervals(std::vector &intervals) {
std::vector merged;
for (auto &interval : intervals) {
if (merged.empty() || merged.back()[1] < interval[0]) {
merged.push_back(interval);
} else {
merged.back()[1] = std::max(merged.back()[1], interval[1]);
}
}
return merged;
}Solution
Step 1: Check preconditions for merging
Merging requires intervals sorted by start time to work correctly.Step 2: Identify missing sorting step
The code does not sort intervals before merging, so overlapping intervals may be missed.Final Answer:
Intervals are not sorted before merging -> Option CQuick Check:
Sort intervals first to merge correctly [OK]
- Skipping sorting step
- Assuming input is sorted
- Misusing std::max function
[[1,4],[4,5],[7,9],[8,10]], what is the merged output after applying the merge overlapping intervals algorithm?Solution
Step 1: Sort intervals by start time
Intervals are already sorted: [1,4], [4,5], [7,9], [8,10]Step 2: Merge overlapping or touching intervals
[1,4] and [4,5] touch at 4, merge to [1,5]. [7,9] and [8,10] overlap, merge to [7,10].Final Answer:
[[1,5],[7,10]] -> Option DQuick Check:
Touching intervals merge too [OK]
- Not merging intervals that touch at endpoints
- Leaving intervals separate when they overlap
- Merging all intervals incorrectly into one
Ready to prove it?
Pass the test and this pattern moves unknown
