1. Phase 1: before
Copy intervals that end before the new one starts.
while (i < n && intervals[i][1] < start) {Typorithm · medium
Step 1 of 8 · intro card
Intervals
On already-sorted intervals, copy those before, merge all overlapping into the new one, then copy those after.
The input is already sorted, so the work splits into three clean phases.
First copy intervals entirely before the new one; then merge every interval that overlaps it, growing its bounds.
Finally append the merged interval and copy the rest, all in a single linear pass.
Three phases: before, overlap, after.
Grow new interval with min/max.
Linear pass on sorted input.
function insert(intervals, newInterval) {
const result = [];
let [start, end] = newInterval;
let i = 0;
const n = intervals.length;
while (i < n && intervals[i][1] < start) {
result.push(intervals[i]);
i += 1;
}
while (i < n && intervals[i][0] <= end) {
start = Math.min(start, intervals[i][0]);
end = Math.max(end, intervals[i][1]);
i += 1;
}
result.push([start, end]);
while (i < n) {
result.push(intervals[i]);
i += 1;
}
return result;
}Connect each part of the code to the concept before you type.
Copy intervals that end before the new one starts.
while (i < n && intervals[i][1] < start) {Absorb every interval that overlaps the new one.
while (i < n && intervals[i][0] <= end) {Stretch the new interval to cover each overlap.
start = Math.min(start, intervals[i][0]);
end = Math.max(end, intervals[i][1]);Copy the remaining non-overlapping intervals.
while (i < n) {Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.