My Calendar III
Hard
Topics
You are given a list of bookings where bookings[i] = [start, end] represents a half-open interval [start, end).
Book them one at a time, in order. A k-booking happens when k events have a non-empty intersection. After each booking, record the largest k such that a k-booking exists.
Return the array of those values.
The original problem is a class with a book method called repeatedly. This judge passes the whole call sequence at once and asks for the answer after each call — the same state machine, batched.
Example 1
book call must return the k-highest overlap seen so far, counting every booking including the new one. After all of these, the peak is 3 (the shaded lanes, all live at time 10).Input: bookings = [[10,20],[50,60],[10,40],[5,15],[5,10],[25,55]] Output: [1,1,2,3,3,3]
Example 2
Input: bookings = [[1,2],[1,2],[1,2]] Output: [1,2,3]
Constraints
- 1 <= bookings.length <= 400
- 0 <= start < end <= 10^9
Editorial — intuition, approach, complexity and pitfalls
Intuition
Maximum overlap is a sweep-line problem. Keep a map from time point to a running delta: +1 where an interval starts and -1 where it ends. Walking the map in time order and accumulating those deltas gives the number of active intervals at each point, and the largest running total is the answer. Because the map stays sorted by time, each new booking just adds two entries and triggers one re-sweep.
Approach
- Keep an ordered map
deltafrom time to net change, persisting across bookings. - For a new booking
[start, end), dodelta[start] += 1anddelta[end] -= 1. - Sweep the keys in increasing time order, accumulating a running
activecount and tracking its maximum. That maximum is the current answer. - Half-open intervals make the boundary case free: an event ending exactly where another starts contributes
-1and+1at the same point, so they never count as overlapping. - Append the maximum after each booking. For larger inputs, a dynamic segment tree with lazy propagation replaces the re-sweep.
class Solution:
def bookAll(self, bookings):
delta = {}
out = []
for start, end in bookings:
delta[start] = delta.get(start, 0) + 1
delta[end] = delta.get(end, 0) - 1
active = 0
best = 0
for t in sorted(delta):
active += delta[t]
best = max(best, active)
out.append(best)
return outDry Run
bookings in order: [10,20] [50,60] [10,40] [5,15] [5,10] [25,55]
`deltas` is a sweep line: +1 at every start, -1 at every end. After each
booking, sort the points and walk them, tracking the running overlap.
add [10,20] deltas 10:+1 20:-1 peak 1 -> 1
add [50,60] 50:+1 60:-1 as well peak 1 -> 1
add [10,40] 10 becomes +2 peak 2 -> 2
add [5,15] 5:+1, 15:-1 peak 3 -> 3
add [5,10] 5 becomes +2, 10 net +1 peak 3 -> 3
add [25,55] 25:+1, 55:-1 peak 3 -> 3
answer 1 1 2 3 3 3
Two things worth noticing. The counter never has to know which bookings
overlap, only how many are open at each point -- that is what makes a sweep line
cheaper than comparing intervals pairwise. And an end at the same point as a
start cancels, which is why [5,10] and [10,20] do not stack: the -1 at 10 is
applied in the same step as the +1.Complexity
- Time — O(n^2 log n) — a sorted sweep after each of the n bookings.
- Space — O(n) — two map entries per booking.
Common Pitfalls
- Order matters when accumulating at a shared time point: the
-1and+1must be summed into the same key, which a delta map does automatically. Storing them as separate list entries and sorting badly can report a phantom overlap. - Reset
activeandbestat the start of every sweep, but never cleardelta— bookings accumulate. - Treating intervals as closed
[start, end]over-counts touching events. The problem is half-open. - Coordinates go up to 10^9, so a plain array indexed by time is not viable — use a map or coordinate compression.
Full Solution — all languages
class Solution:
def bookAll(self, matrix):
deltas = {}
out = []
for start, end in matrix:
deltas[start] = deltas.get(start, 0) + 1
deltas[end] = deltas.get(end, 0) - 1
running = 0
best = 0
for point in sorted(deltas):
running += deltas[point]
best = max(best, running)
out.append(best)
return outimport java.util.*;
class Solution {
public java.util.List<Integer> bookAll(int[][] matrix) {
TreeMap<Integer, Integer> deltas = new TreeMap<>();
List<Integer> out = new ArrayList<>();
for (int[] booking : matrix) {
deltas.merge(booking[0], 1, Integer::sum);
deltas.merge(booking[1], -1, Integer::sum);
int running = 0, best = 0;
for (int delta : deltas.values()) {
running += delta;
best = Math.max(best, running);
}
out.add(best);
}
return out;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> bookAll(vector<vector<int>>& matrix) {
map<int, int> deltas;
vector<int> out;
for (auto& booking : matrix) {
deltas[booking[0]]++;
deltas[booking[1]]--;
int running = 0, best = 0;
for (auto& kv : deltas) {
running += kv.second;
best = max(best, running);
}
out.push_back(best);
}
return out;
}
};/**
* @param {number[][]} matrix
* @return {number[]}
*/ var bookAll = function(matrix) {
const deltas = new Map();
const out = [];
for (const booking of matrix) {
deltas.set(booking[0], (deltas.get(booking[0]) || 0) + 1);
deltas.set(booking[1], (deltas.get(booking[1]) || 0) - 1);
let running = 0, best = 0;
for (const point of [...deltas.keys()].sort((a, b) => a - b)) {
running += deltas.get(point);
best = Math.max(best, running);
}
out.push(best);
}
return out;
};