AlgoTales · Roadmap

Interval scheduling

Intermediate · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Interval scheduling is the everyday task of fitting as many time ranges as possible onto one resource without overlap. It is the same idea as activity selection, applied to bookings, and the winning move is to favour whatever ends first.

Practical use cases

  • Web app: One cricket net for many teams. A sports club app has requests from teams with start and end times for a single practice net. Sorting by end time and accepting every request that does not clash lets the most teams practise on Saturday. Teams that are turned away can be offered the next free slot automatically.
  • Web app: Lab equipment booking. A research portal has one microscope and many requests. The same rule books the most sessions, and the leftover requests are shown "try another slot".
  • Web app: Radio or streaming slot planner. A web radio has shows proposed for one channel. Choosing by earliest end packs in the most programmes for the day, and the planner does not have to shuffle times by hand.
  • System: Doctor and venue appointments. Hospitals and venues use this method to decide how many bookings a single room or doctor can serve. It is the same idea each time: a single resource, many time ranges, and the choice that frees it up earliest wins.

The story: Aarav's Cricket Net

Aarav ran the practice net behind the mohalla ground. On Sunday, five teams asked for time slots, but the single net could host only one team at a time. Some requests overlapped, so he had to say "sorry" to a few teams.

Nobody likes saying sorry, so he wanted to cancel as few bookings as possible. He first tried to cancel the longest ones. But that sometimes left two short, tricky overlaps still standing, and he had to start over.

Mrs. Sharma, who knew this problem well, gave him a cleaner way: "Sort the bookings by when they end. Keep the first. For each next booking, if it starts before the last kept one ends, cancel it. Otherwise keep it." The booking that ends earliest hurts the future the least.

Aarav ended up cancelling only two. That is interval scheduling (also called "non-overlapping intervals"). One warning from Mrs. Sharma: if each booking pays a different amount and you want the most money, this plain greedy can fail, and you need dynamic programming.

How to spot this problem, and where you need it

Many people want the same single room, machine or person at overlapping times, and you must decide which requests to accept so that as many as possible are served.

Signs you need it

  • Requests have a start and an end time, and the resource can only do one at a time.
  • The question is "how many can we accept?" rather than "who pays most?".
  • Accepting requests in the order they arrived blocks lots of later short ones.

Where to use it in a project

  • Venue, pitch, lab or equipment booking portals deciding which requests to approve.
  • Appointment systems for a single doctor, consultant or machine.

The solution

Sort the requests by end time. Keep a variable for the end of the last accepted request. Walk through the sorted list: if a request starts at or after that end, accept it and update the end; otherwise reject it. The one that ends first leaves the most room, and the count of accepted requests is the largest possible.

Payoff: Before: first-come booking served 5 teams. After: end-time-first served 8 teams on the same net.

Explain it like I am 8

Many kids want the same swing, each with their own start and end time. Always keep the kid who gets off the swing first. Anyone who wants to start while that kid is still swinging has to wait or go home.

How it works, step by step

  1. Sort the intervals by their end value.
  2. Keep the first one and remember its end as end.
  3. For each next interval: if its start is >= end, keep it and update end.
  4. Otherwise it overlaps, so count it as removed.
  5. The answer to "fewest removals" is the number of intervals you skipped.

The code in four languages

PHP

<?php
// How many intervals must we remove so that none overlap? (Touching ends are fine.)
function eraseOverlaps(array $iv): int {
    if (count($iv) === 0) return 0;
    usort($iv, fn($a, $b) => $a[1] <=> $b[1]);     // earliest end first
    $end = $iv[0][1];                              // keep the first one
    $removed = 0;
    for ($i = 1; $i < count($iv); $i++) {
        if ($iv[$i][0] >= $end) {
            $end = $iv[$i][1];                     // no clash: keep it
        } else {
            $removed++;                            // clash: cancel it
        }
    }
    return $removed;
}

echo eraseOverlaps([[1, 2], [2, 3], [3, 4], [1, 3], [2, 4]]);   // 2

JavaScript

// How many intervals must we remove so that none overlap? (Touching ends are fine.)
function eraseOverlaps(iv) {
  if (iv.length === 0) return 0;
  iv = [...iv].sort((a, b) => a[1] - b[1]);        // earliest end first
  let end = iv[0][1];                              // keep the first one
  let removed = 0;
  for (let i = 1; i < iv.length; i++) {
    if (iv[i][0] >= end) {
      end = iv[i][1];                              // no clash: keep it
    } else {
      removed++;                                   // clash: cancel it
    }
  }
  return removed;
}

console.log(eraseOverlaps([[1, 2], [2, 3], [3, 4], [1, 3], [2, 4]]));   // 2

Java

import java.util.*;

public class Main {
    // How many intervals must we remove so that none overlap? (Touching ends are fine.)
    static int eraseOverlaps(int[][] input) {
        if (input.length == 0) return 0;
        int[][] iv = input.clone();
        Arrays.sort(iv, (a, b) -> Integer.compare(a[1], b[1]));   // earliest end first
        int end = iv[0][1];                                       // keep the first one
        int removed = 0;
        for (int i = 1; i < iv.length; i++) {
            if (iv[i][0] >= end) {
                end = iv[i][1];                                   // no clash: keep it
            } else {
                removed++;                                        // clash: cancel it
            }
        }
        return removed;
    }

    public static void main(String[] args) {
        System.out.println(eraseOverlaps(new int[][]{{1, 2}, {2, 3}, {3, 4}, {1, 3}, {2, 4}}));   // 2
    }
}

Go

package main

import (
	"cmp"
	"fmt"
	"slices"
)

// eraseOverlaps: how many intervals must we remove so that none overlap? (Touching ends are fine.)
func eraseOverlaps(input [][2]int) int {
	if len(input) == 0 {
		return 0
	}
	iv := slices.Clone(input)
	slices.SortFunc(iv, func(a, b [2]int) int { return cmp.Compare(a[1], b[1]) }) // earliest end first
	end := iv[0][1]                                                               // keep the first one
	removed := 0
	for _, cur := range iv[1:] {
		if cur[0] >= end {
			end = cur[1] // no clash: keep it
		} else {
			removed++ // clash: cancel it
		}
	}
	return removed
}

func main() {
	fmt.Println(eraseOverlaps([][2]int{{1, 2}, {2, 3}, {3, 4}, {1, 3}, {2, 4}})) // 2
}

Time: O(n log n) · Extra space: O(1). Sorting dominates. The single pass only remembers one number: the end of the last kept interval (extra space is tiny apart from the sort).

Watch out for

  • Sorting by start time. A very long early interval can block many short ones.
  • Treating touching intervals (end 3, start 3) as overlapping.
  • Using this plain greedy when intervals have different weights (profits). That needs dynamic programming.

Quick check

  1. How do we sort the intervals to remove the fewest?
    • By end
    • By start
    • By length
  2. Total intervals minus the biggest non-overlapping set equals...?
    • The longest interval
    • The number of gaps
    • The minimum number of removals
  3. When might this greedy fail?
    • When intervals are sorted
    • When each interval has a different value and we want max total value
    • When intervals touch