Skip to the content

Lesson 144 of 296

Intervals

What you will learn

  • The "sort by start, then sweep" pattern
  • When two intervals overlap
  • Merge Intervals
  • Insert Interval
  • Non-overlapping Intervals
  • Meeting Rooms I and II
On this page

Intervals

An interval is a range [start, end]: a booking, a meeting, a shift, a time slot. Interval problems are very common in interviews and in real business systems (booking clash checks, calendars, rotas).

Two intervals [a, b] and [c, d] overlap when:

a < d && c < b

(Use <= if touching ends count as overlapping, for example if a meeting ending at 10:00 clashes with one starting at 10:00. Always ask.)

The pattern: sort by start, then sweep

After sorting by start time, any interval can only overlap with the one just before it in the result, so one pass is enough. Sorting costs O(n log n), which is usually the total cost.

Merge Intervals

Problem (LeetCode 56): merge all overlapping intervals.
[[1, 3], [2, 6], [8, 10], [15, 18]] → [[1, 6], [8, 10], [15, 18]].

TypeScript
function mergeIntervals(intervals: [number, number][]): [number, number][] {
  const sorted = [...intervals].sort((a, b) => a[0] - b[0]);
  const merged: [number, number][] = [];
  for (const [start, end] of sorted) {
    const last = merged.at(-1);
    if (last !== undefined && start <= last[1]) {
      last[1] = Math.max(last[1], end);
    } else {
      merged.push([start, end]);
    }
  }
  return merged;
}

Math.max matters: [1, 10] followed by [2, 3] must stay [1, 10], not shrink to [1, 3]. O(n log n) time.

Insert Interval

Problem (LeetCode 57): a list of non-overlapping intervals already sorted by start. Insert a new interval, merging if needed.
intervals = [[1, 3], [6, 9]], newInterval = [2, 5] → [[1, 5], [6, 9]].

Three phases in one pass:

  1. Add every interval that ends before the new one starts.
  2. Merge every interval that overlaps the new one.
  3. Add the rest.
TypeScript
function insertInterval(intervals: [number, number][], newInterval: [number, number]): [number, number][] {
  const result: [number, number][] = [];
  let [start, end] = newInterval;
  let i = 0;
  while (i < intervals.length && intervals[i]![1] < start) {
    result.push(intervals[i]!);
    i++;
  }
  while (i < intervals.length && intervals[i]![0] <= end) {
    start = Math.min(start, intervals[i]![0]);
    end = Math.max(end, intervals[i]![1]);
    i++;
  }
  result.push([start, end]);
  while (i < intervals.length) {
    result.push(intervals[i]!);
    i++;
  }
  return result;
}

O(n): no sorting needed because the input is already sorted.

Non-overlapping Intervals

Problem (LeetCode 435): the minimum number of intervals to remove so the rest do not overlap.
[[1, 2], [2, 3], [3, 4], [1, 3]] → 1.

Greedy idea (Lesson 145): sort by end time. Always keep the interval that ends earliest, because it leaves the most room for the others. Remove anything that overlaps the last kept one.

TypeScript
function eraseOverlapIntervals(intervals: [number, number][]): number {
  const sorted = [...intervals].sort((a, b) => a[1] - b[1]);
  let removed = 0;
  let lastEnd = -Infinity;
  for (const [start, end] of sorted) {
    if (start >= lastEnd) {
      lastEnd = end;
    } else {
      removed++;
    }
  }
  return removed;
}

(Here touching intervals such as [1, 2] and [2, 3] do not overlap.) This is the classic "activity selection" problem.

Meeting Rooms

Problem (LeetCode 252): can one person attend all meetings? Sort by start and check neighbours.

TypeScript
function canAttendMeetings(meetings: [number, number][]): boolean {
  const sorted = [...meetings].sort((a, b) => a[0] - b[0]);
  for (let i = 1; i < sorted.length; i++) {
    if (sorted[i]![0] < sorted[i - 1]![1]) return false;
  }
  return true;
}

Meeting Rooms II

Problem (LeetCode 253): the minimum number of rooms needed for all meetings.
[[0, 30], [5, 10], [15, 20]] → 2.

Sweep with events: split every meeting into a start event (+1 room) and an end event (−1 room). Sort the starts and the ends separately and walk through them in time order, tracking how many rooms are in use.

TypeScript
function minMeetingRooms(meetings: [number, number][]): number {
  const starts = meetings.map((m) => m[0]).sort((a, b) => a - b);
  const ends = meetings.map((m) => m[1]).sort((a, b) => a - b);
  let rooms = 0;
  let best = 0;
  let e = 0;
  for (const start of starts) {
    while (e < ends.length && ends[e]! <= start) {
      rooms--;
      e++;
    }
    rooms++;
    best = Math.max(best, rooms);
  }
  return best;
}

ends[e] <= start means a meeting that ends exactly when another starts frees its room in time. O(n log n). (A min-heap of end times also works: the top is the room that frees up first.)

Real-world: booking clash check

A practical task from the study plan (Lesson 155 builds it fully): "does a new booking overlap any existing booking for this room?" For one check, test the overlap formula against each booking (O(n)), or keep bookings sorted and binary search (O(log n)). In a database, the same rule becomes a query or an exclusion constraint (Part 17).

How to say it in an interview

"Two intervals overlap when each starts before the other ends. Most interval problems sort by start and sweep once, comparing with the last merged interval and extending its end with max. Insert Interval needs no sort: add intervals ending before the new one, merge overlapping ones, then add the rest. For the minimum removals I sort by end and greedily keep the earliest-ending interval. For meeting rooms I sweep sorted start and end times, or keep a min-heap of end times, to find the maximum concurrent meetings."

Key words

WordMeaning
IntervalA range with a start and an end
OverlapTwo intervals sharing some time
SweepProcessing events in sorted order
Activity selectionChoosing the most non-overlapping intervals

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.