Insert Interval into Sorted List in DSA Javascript - Time & Space Complexity
We want to know how the time to insert a new interval into a sorted list grows as the list gets bigger.
Specifically, how many steps does it take to find the right place and merge intervals if needed?
Analyze the time complexity of the following code snippet.
function insertInterval(intervals, newInterval) {
const result = [];
let i = 0;
while (i < intervals.length && intervals[i][1] < newInterval[0]) {
result.push(intervals[i]);
i++;
}
while (i < intervals.length && intervals[i][0] <= newInterval[1]) {
newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
i++;
}
result.push(newInterval);
while (i < intervals.length) {
result.push(intervals[i]);
i++;
}
return result;
}
This code inserts a new interval into a sorted list of intervals and merges overlapping ones.
Look for loops and repeated steps.
- Primary operation: Three while loops that each scan parts of the intervals list.
- How many times: Each interval is visited once in total across the loops.
As the number of intervals grows, the code checks each interval once.
| 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 steps grow roughly in direct proportion to the number of intervals.
Time Complexity: O(n)
This means the time to insert and merge grows linearly with the number of intervals.
[X] Wrong: "Since we merge intervals, the time must be more than linear, maybe quadratic."
[OK] Correct: Each interval is visited only once, and merging happens during that single pass, so the time stays linear.
Understanding this linear time approach shows you can handle merging problems efficiently, a common skill interviewers look for.
"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 with no overlaps, and we want to insert a new interval.Step 2: Identify the correct approach
We must merge any intervals that overlap with the new one and keep the list sorted.Final Answer:
To merge overlapping intervals and keep the list sorted -> Option BQuick Check:
Insert interval = merge and sort [OK]
- Inserting without merging overlaps
- Appending without sorting
- Removing unrelated intervals
Solution
Step 1: Recall JavaScript array methods
JavaScript arrays use push() to add elements at the end.Step 2: Match method to syntax
push() is correct; insert(), add(), and append() are not valid JavaScript array methods.Final Answer:
intervals.push([3,5]) -> Option AQuick Check:
Use push() to add elements in JS arrays [OK]
- Using insert() which is not a JS array method
- Using add() or append() from other languages
- Forgetting to add as an array element
const intervals = [[1,2],[5,6]];
const newInterval = [3,5];
function insertInterval(intervals, newInterval) {
const result = [];
let i = 0;
while (i < intervals.length && intervals[i][1] < newInterval[0]) {
result.push(intervals[i]);
i++;
}
while (i < intervals.length && intervals[i][0] <= newInterval[1]) {
newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
i++;
}
result.push(newInterval);
while (i < intervals.length) {
result.push(intervals[i]);
i++;
}
return result;
}
console.log(insertInterval(intervals, newInterval));Solution
Step 1: Process intervals before newInterval
Intervals before newInterval are [[1,2]] because 2 < 3, so push [1,2].Step 2: Merge overlapping intervals
Intervals overlapping with newInterval are [5,6] because 5 <= 5. Merge [3,5] and [5,6] to get [3,6].Step 3: Add merged interval and remaining intervals
Push merged [3,6]. No intervals left after merging.Final Answer:
[[1,2],[3,6]] -> Option DQuick Check:
Merged intervals = [[1,2],[3,6]] [OK]
- Not merging overlapping intervals
- Adding newInterval multiple times
- Incorrectly ordering intervals after merge
function insert(intervals, newInterval) {
let result = [];
let i = 0;
while (i < intervals.length && intervals[i][1] < newInterval[0]) {
result.push(intervals[i]);
i++;
}
while (i < intervals.length && intervals[i][0] < newInterval[1]) {
newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
i++;
}
result.push(newInterval);
while (i < intervals.length) {
result.push(intervals[i]);
i++;
}
return result;
}Solution
Step 1: Analyze the second while loop condition
The second loop merges overlapping intervals. It uses intervals[i][0] < newInterval[1], which misses intervals starting exactly at newInterval[1].Step 2: Correct the condition
Change < to <= to include intervals starting at newInterval[1] for proper merging.Final Answer:
The second while condition should use <= instead of < -> Option CQuick Check:
Use <= to merge intervals starting at newInterval[1] [OK]
- Using < instead of <= in merge condition
- Pushing newInterval too early
- Not initializing result array
Solution
Step 1: Identify intervals before newInterval
Interval [1,3] overlaps with newInterval [2,5] because 3 >= 2, so no intervals come before without overlap.Step 2: Merge overlapping intervals
Merge [1,3] and [2,5] to get [1,5]. Interval [6,9] does not overlap and stays as is.Final Answer:
[[1,5],[6,9]] -> Option AQuick Check:
Merged intervals = [[1,5],[6,9]] [OK]
- Not merging overlapping intervals
- Adding newInterval without merging
- Merging unrelated intervals
Ready to prove it?
Pass the test and this pattern moves unknown
