Skip to content

Start typing to search patterns, problems and pages.

Intervals

Lay every meeting of a shared day on one timeline in start order. Meetings that overlap or touch fuse into one busy block. What is left is the day’s true shape, with every gap visible.

⏱ about 15 minutesNeeds: sorting, arraysTime O(n log n)Space O(n)

2 · Watch

Intervals in 60 seconds

Four bookings cover 8–10, 1–3, 15–18 and 2–6. Which busy blocks do they really form? Comparing every pair means six checks.

3 · Now you drive

Keys:←→ stepSpace playR resetHomeEnd jump

Merge Intervals

or try
1–6 intervals like 1-3, with 0 ≤ start ≤ end ≤ 20, separated by spaces.
Here are the intervals as bars on a number line.Step 1 of 7. 4 intervals on a 0 to 20 line: 8 to 10, 1 to 3, 15 to 18, 2 to 6. Not sorted yet.
Step 1 of 7
solution.ts
function merge(intervals: number[][]): number[][] {
intervals.sort((a, b) => a[0] - b[0]);
const merged: number[][] = [intervals[0]];
for (let i = 1; i < intervals.length; i++) {
const last = merged[merged.length - 1];
const [start, end] = intervals[i];
if (start <= last[1]) {
last[1] = Math.max(last[1], end);
} else {
merged.push([start, end]);
}
}
return merged;
}
▶ marks the line running now

4 · Your turn

0 of 5 problems solved

Start from this

if (intervals.length === 0) return [];
// Sort by start, so overlaps end up side by side.
intervals.sort((a, b) => a[0] - b[0]);
const out = [intervals[0]];
for (const [start, end] of intervals.slice(1)) {
  const last = out[out.length - 1];
  // Overlap: extend the last one to the later end.
  if (start <= last[1]) last[1] = Math.max(last[1], end);
  // No overlap: this one starts a new interval.
  else out.push([start, end]);
}

Easy ways to go wrong

  • Forgetting to sort first.
  • Replacing the end with the new end. Take the max, since one may contain the other.
  • Deciding whether touching ends count as overlap. Read the problem.
  • Sorting by start when you must remove the fewest. Sort by end, so you keep whichever finishes first.
  1. Easy01

    Meeting Rooms

    LeetCode 252 · Blind 75 · NeetCode 150

    LeetCode Premium

    Warm-up: sort by start; any overlap means a clash.

  2. Medium02

    Merge Intervals

    LeetCode 56 · Blind 75 · NeetCode 150

    The one you just watched. Write it from memory.

  3. Medium03

    Insert Interval

    LeetCode 57 · Blind 75 · NeetCode 150

    Slide the new interval into its sorted slot, then merge.

  4. Medium04

    Non-overlapping Intervals

    LeetCode 435 · Blind 75 · NeetCode 150

    Count the overlaps to remove instead of merging them.

  5. Medium05

    Meeting Rooms II

    LeetCode 253 · Blind 75 · NeetCode 150

    LeetCode Premium

    Track how many meetings run at once; keep the peak.

UP NEXT · LESSON 19 OF 20Math & GeometryWalk and transform grids with simple coordinates.