Insert Interval into Sorted List in DSA C++ - 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 a new interval to the list?
Analyze the time complexity of the following code snippet.
vector<vector<int>> insertInterval(vector<vector<int>> &intervals, vector<int> &newInterval) {
vector<vector<int>> result;
int i = 0, n = intervals.size();
while (i < n && intervals[i][1] < newInterval[0]) {
result.push_back(intervals[i++]);
}
while (i < n && intervals[i][0] <= newInterval[1]) {
newInterval[0] = min(newInterval[0], intervals[i][0]);
newInterval[1] = max(newInterval[1], intervals[i][1]);
i++;
}
result.push_back(newInterval);
while (i < n) {
result.push_back(intervals[i++]);
}
return result;
}
This code inserts a new interval into a sorted list of intervals, merging overlapping intervals as needed.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Three while loops that traverse the intervals list.
- How many times: Each loop runs over parts of the list without overlap, together covering all intervals once.
The code goes through the list of intervals once, splitting the work into three parts but never revisiting intervals.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps to check and insert intervals |
| 100 | About 100 steps, each interval checked once |
| 1000 | About 1000 steps, linear growth |
Pattern observation: The number of steps grows directly with the number of intervals; doubling intervals roughly doubles the work.
Time Complexity: O(n)
This means the time to insert grows linearly with the number of intervals in the list.
[X] Wrong: "Since there are three loops, the time complexity is O(3n) or O(n²)."
[OK] Correct: The loops run one after another, each covering different parts of the list without overlap, so total work is still proportional to n, not n squared.
Understanding how to analyze linear scans like this is a key skill. It shows you can break down code into parts and see how they add up to total work.
"What if the intervals list was not sorted? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem context
We have a sorted list of intervals that do not overlap. When inserting a new interval, we must keep the list sorted and merge any overlapping intervals.Step 2: Identify the correct approach
Simply adding the new interval without merging can cause overlaps. Sorting again without merging breaks the non-overlapping property. Removing intervals before the new one is incorrect.Final Answer:
To merge overlapping intervals and keep the list sorted -> Option AQuick Check:
Insert Interval = Merge and keep sorted [OK]
- Inserting without merging overlaps
- Sorting intervals again without merging
- Removing intervals unnecessarily
Solution
Step 1: Understand vector and pair syntax
In C++, a vector of pairs is declared as std::vector>. The pair must specify both types inside angle brackets.Step 2: Check each option
std::vector> intervals; correctly uses std::pair. std::vector intervals; is invalid syntax for vector. std::vector intervals; misses the second type in pair. std::vector intervals; misses template parameters for pair.Final Answer:
std::vector> intervals; -> Option DQuick Check:
Vector of pairs syntax = std::vector> intervals; [OK]
- Missing template parameters in pair
- Incorrect vector declaration syntax
- Using incomplete pair types
[(1, 3), (6, 9)] and a new interval (2, 5), what will be the resulting list after insertion and merging?Solution
Step 1: Identify overlapping intervals
The new interval (2, 5) overlaps with (1, 3) because 2 <= 3. They should be merged into (1, 5).Step 2: Merge and keep other intervals
After merging (1, 3) and (2, 5) into (1, 5), the interval (6, 9) remains unchanged.Final Answer:
[(1, 5), (6, 9)] -> Option BQuick Check:
Merge overlapping intervals = [(1, 5), (6, 9)] [OK]
- Not merging overlapping intervals
- Inserting without sorting
- Merging all intervals incorrectly
std::vector> insertInterval(std::vector>& intervals, std::pair newInterval) {
std::vector> result;
int i = 0;
while (i < intervals.size() && intervals[i].second < newInterval.first) {
result.push_back(intervals[i]);
i++;
}
while (i < intervals.size() && intervals[i].first <= newInterval.second) {
newInterval.first = std::min(newInterval.first, intervals[i].first);
newInterval.second = std::max(newInterval.second, intervals[i].second);
i++;
}
result.push_back(newInterval);
while (i < intervals.size()) {
result.push_back(intervals[i]);
i++;
}
return result;
}
What is the bug in this code if any?Solution
Step 1: Analyze the first while loop
The first loop adds all intervals that end before the new interval starts, correctly skipping non-overlapping intervals before newInterval.Step 2: Analyze the second while loop
The second loop merges all intervals overlapping with newInterval by updating its start and end correctly.Step 3: Analyze the final steps
After merging, newInterval is added, then remaining intervals are appended. This maintains sorted order and merges properly.Final Answer:
No bug; the code correctly inserts and merges intervals -> Option AQuick Check:
Code logic matches insert and merge steps [OK]
- Changing loop conditions incorrectly
- Pushing newInterval too early or late
- Merging intervals incorrectly
[(1, 2), (3, 5), (6, 7), (8, 10), (12, 16)]. You want to insert a new interval (4, 8). What is the final list after insertion and merging?Solution
Step 1: Identify intervals overlapping with (4, 8)
Intervals (3, 5), (6, 7), and (8, 10) overlap with (4, 8) because their ranges intersect.Step 2: Merge all overlapping intervals
Merge (3, 5), (6, 7), (8, 10), and (4, 8) into one interval. The merged interval starts at min(3,4,6,8) = 3 and ends at max(5,7,8,10) = 10.Step 3: Keep non-overlapping intervals
Intervals (1, 2) and (12, 16) remain unchanged.Final Answer:
[(1, 2), (3, 10), (12, 16)] -> Option CQuick Check:
Merge overlapping intervals = [(1, 2), (3, 10), (12, 16)] [OK]
- Not merging all overlapping intervals
- Inserting new interval without merging
- Incorrect interval boundaries after merge
Ready to prove it?
Pass the test and this pattern moves unknown
