Typorithm · medium

Interval Scheduling

▷ Interactive algorithm labinterval-schedulinggreedyintervalssortinggreedy-choice
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Interval Scheduling

0%

Greedy

Sort by finish time, then keep every interval that starts after the last kept one ends.

The goal is to keep as many non-overlapping intervals as possible.

The greedy choice is to always keep the interval that finishes earliest, because it leaves the most room for the rest.

Sorting by finish time once, then a single linear scan, gives the optimal answer.

Preparing algorithm lab…
01

Sort by finish time, not start time.

02

Greedy pick: earliest finish that fits.

03

Keep when start >= last finish.

function maxNonOverlapping(intervals) {
  intervals.sort((a, b) => a[1] - b[1]);

  let count = 0;
  let end = -Infinity;

  for (const [start, finish] of intervals) {
    if (start >= end) {
      count += 1;
      end = finish;
    }
  }

  return count;
}

Read the implementation

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

1. Sort by finish

Sorting by finish time makes the earliest-ending interval the safe greedy pick.

intervals.sort((a, b) => a[1] - b[1])

2. Last finish

Track the finish time of the last interval we kept.

let end = -Infinity

3. Scan in order

Walk the intervals from earliest finish to latest.

for (const [start, finish] of intervals)

4. No overlap

Keep an interval only when it starts at or after the last kept finish.

if (start >= end)

5. Advance end

After keeping an interval, its finish becomes the new boundary.

end = finish

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.

Interval Scheduling: Visual Walkthrough & Practice · Typorithm | ApplyDjinn