Typorithm · medium

Insert Interval

insert-intervalintervalsthree-phasesmergesorted-input
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Insert Interval

0%

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.

01

Three phases: before, overlap, after.

02

Grow new interval with min/max.

03

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;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Phase 1: before

Copy intervals that end before the new one starts.

while (i < n && intervals[i][1] < start) {

2. Phase 2: overlap

Absorb every interval that overlaps the new one.

while (i < n && intervals[i][0] <= end) {

3. Grow the new interval

Stretch the new interval to cover each overlap.

start = Math.min(start, intervals[i][0]);
    end = Math.max(end, intervals[i][1]);

4. Phase 3: after

Copy the remaining non-overlapping intervals.

while (i < n) {

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Insert Interval: Lesson & Practice · Typorithm | ApplyDjinn