Merge, insert and schedule intervals after sorting by start.
After sorting by start, the open block is the union of the slots that reach it, and no later slot can join an earlier block.
Use it when events have a start and an end. You may need to join them, add one, count how many run at once, or find the time two lists share. Signal words: overlap, join, free time, at the same time, double booked, add a booking.
Start: sort by start, unless the list is already sorted. Say which ends count.
Step: compare the next slot with the end of the open block. Join it, or start a new block.
Stop: when the list is used up. For two lists, stop when one of them is used up.
It does not pick the most events that fit together. That needs a sort by end time.
Cost: O(n log n) for the sort, and O(n) for one scan. Insert and intersect read sorted lists, so they cost O(n + m).
def merge_intervals(slots):
# [1] Sort by start, so every slot that can join the open block comes right after it.
ordered = sorted(slots)
merged = []
for start, end in ordered:
if merged and start <= merged[-1][1]:
# [2] A slot that starts at or before the open block's end shares a slot with it: it joins, and the block keeps the larger end.
merged[-1][1] = max(merged[-1][1], end)
else:
# [3] Otherwise the slot starts a new block.
merged.append([start, end])
# [4] Return the blocks, sorted by start.
return mergedpublic int[][] mergeIntervals(int[][] slots) {
// [1] Sort by start, so every slot that can join the open block comes right after it.
int[][] ordered = slots.clone();
Arrays.sort(ordered, (a, b) -> Integer.compare(a[0], b[0]));
List<int[]> merged = new ArrayList<>();
for (int[] slot : ordered) {
if (!merged.isEmpty() && slot[0] <= merged.get(merged.size() - 1)[1]) {
// [2] A slot that starts at or before the open block's end shares a slot with it: it joins, and the block keeps the larger end.
int[] open = merged.get(merged.size() - 1);
open[1] = Math.max(open[1], slot[1]);
} else {
// [3] Otherwise the slot starts a new block.
merged.add(new int[] {slot[0], slot[1]});
}
}
// [4] Return the blocks, sorted by start.
return merged.toArray(new int[0][]);
}vector<vector<int>> mergeIntervals(const vector<vector<int>>& slots) {
// [1] Sort by start, so every slot that can join the open block comes right after it.
vector<vector<int>> ordered = slots;
sort(ordered.begin(), ordered.end());
vector<vector<int>> merged;
for (const auto& slot : ordered) {
if (!merged.empty() && slot[0] <= merged.back()[1]) {
// [2] A slot that starts at or before the open block's end shares a slot with it: it joins, and the block keeps the larger end.
merged.back()[1] = max(merged.back()[1], slot[1]);
} else {
// [3] Otherwise the slot starts a new block.
merged.push_back({slot[0], slot[1]});
}
}
// [4] Return the blocks, sorted by start.
return merged;
}function mergeIntervals(slots) {
// [1] Sort by start, so every slot that can join the open block comes right after it.
const ordered = [...slots].sort((a, b) => a[0] - b[0]);
const merged = [];
for (const [start, end] of ordered) {
if (merged.length > 0 && start <= merged[merged.length - 1][1]) {
// [2] A slot that starts at or before the open block's end shares a slot with it: it joins, and the block keeps the larger end.
merged[merged.length - 1][1] = Math.max(merged[merged.length - 1][1], end);
} else {
// [3] Otherwise the slot starts a new block.
merged.push([start, end]);
}
}
// [4] Return the blocks, sorted by start.
return merged;
}def insert_slot(slots, new_slot):
start, end = new_slot
result = []
i = 0
n = len(slots)
# [1] Copy every slot that ends before the new slot starts: it shares no slot with it.
while i < n and slots[i][1] < start:
result.append(slots[i])
i += 1
# [2] Absorb every slot that starts at or before the new slot's end: the new slot grows to cover it.
while i < n and slots[i][0] <= end:
start = min(start, slots[i][0])
end = max(end, slots[i][1])
i += 1
# [3] Place the grown slot, then copy every slot that starts after it.
result.append([start, end])
while i < n:
result.append(slots[i])
i += 1
# [4] Return the new calendar.
return resultpublic int[][] insertSlot(int[][] slots, int[] newSlot) {
int start = newSlot[0];
int end = newSlot[1];
List<int[]> result = new ArrayList<>();
int i = 0;
int n = slots.length;
// [1] Copy every slot that ends before the new slot starts: it shares no slot with it.
while (i < n && slots[i][1] < start) {
result.add(slots[i]);
i++;
}
// [2] Absorb every slot that starts at or before the new slot's end: the new slot grows to cover it.
while (i < n && slots[i][0] <= end) {
start = Math.min(start, slots[i][0]);
end = Math.max(end, slots[i][1]);
i++;
}
// [3] Place the grown slot, then copy every slot that starts after it.
result.add(new int[] {start, end});
while (i < n) {
result.add(slots[i]);
i++;
}
// [4] Return the new calendar.
return result.toArray(new int[0][]);
}vector<vector<int>> insertSlot(const vector<vector<int>>& slots, const vector<int>& newSlot) {
int start = newSlot[0];
int end = newSlot[1];
vector<vector<int>> result;
size_t i = 0;
size_t n = slots.size();
// [1] Copy every slot that ends before the new slot starts: it shares no slot with it.
while (i < n && slots[i][1] < start) {
result.push_back(slots[i]);
i++;
}
// [2] Absorb every slot that starts at or before the new slot's end: the new slot grows to cover it.
while (i < n && slots[i][0] <= end) {
start = min(start, slots[i][0]);
end = max(end, slots[i][1]);
i++;
}
// [3] Place the grown slot, then copy every slot that starts after it.
result.push_back({start, end});
while (i < n) {
result.push_back(slots[i]);
i++;
}
// [4] Return the new calendar.
return result;
}function insertSlot(slots, newSlot) {
let [start, end] = newSlot;
const result = [];
let i = 0;
const n = slots.length;
// [1] Copy every slot that ends before the new slot starts: it shares no slot with it.
while (i < n && slots[i][1] < start) {
result.push(slots[i]);
i++;
}
// [2] Absorb every slot that starts at or before the new slot's end: the new slot grows to cover it.
while (i < n && slots[i][0] <= end) {
start = Math.min(start, slots[i][0]);
end = Math.max(end, slots[i][1]);
i++;
}
// [3] Place the grown slot, then copy every slot that starts after it.
result.push([start, end]);
while (i < n) {
result.push(slots[i]);
i++;
}
// [4] Return the new calendar.
return result;
}def most_at_once(meetings):
# [1] Make two events for every meeting: +1 when it starts, -1 when it ends.
events = []
for start, end in meetings:
events.append((start, 1))
events.append((end, -1))
# [2] Sort by time. At the same time an end (-1) comes before a start (+1), because the end minute is free.
events.sort()
busy = 0
most = 0
for time, change in events:
# [3] Apply the event and keep the largest count seen.
busy += change
most = max(most, busy)
# [4] The largest count is the number of rooms needed.
return mostpublic int mostAtOnce(int[][] meetings) {
// [1] Make two events for every meeting: +1 when it starts, -1 when it ends.
int[][] events = new int[meetings.length * 2][];
int k = 0;
for (int[] meeting : meetings) {
events[k++] = new int[] {meeting[0], 1};
events[k++] = new int[] {meeting[1], -1};
}
// [2] Sort by time. At the same time an end (-1) comes before a start (+1), because the end minute is free.
Arrays.sort(events, (a, b) -> a[0] != b[0] ? Integer.compare(a[0], b[0]) : Integer.compare(a[1], b[1]));
int busy = 0;
int most = 0;
for (int[] event : events) {
// [3] Apply the event and keep the largest count seen.
busy += event[1];
most = Math.max(most, busy);
}
// [4] The largest count is the number of rooms needed.
return most;
}int mostAtOnce(const vector<vector<int>>& meetings) {
// [1] Make two events for every meeting: +1 when it starts, -1 when it ends.
vector<pair<int, int>> events;
for (const auto& meeting : meetings) {
events.push_back({meeting[0], 1});
events.push_back({meeting[1], -1});
}
// [2] Sort by time. At the same time an end (-1) comes before a start (+1), because the end minute is free.
sort(events.begin(), events.end());
int busy = 0;
int most = 0;
for (const auto& event : events) {
// [3] Apply the event and keep the largest count seen.
busy += event.second;
most = max(most, busy);
}
// [4] The largest count is the number of rooms needed.
return most;
}function mostAtOnce(meetings) {
// [1] Make two events for every meeting: +1 when it starts, -1 when it ends.
const events = [];
for (const [start, end] of meetings) {
events.push([start, 1]);
events.push([end, -1]);
}
// [2] Sort by time. At the same time an end (-1) comes before a start (+1), because the end minute is free.
events.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
let busy = 0;
let most = 0;
for (const [time, change] of events) {
// [3] Apply the event and keep the largest count seen.
busy += change;
most = Math.max(most, busy);
}
// [4] The largest count is the number of rooms needed.
return most;
}def shared_slots(first, second):
result = []
i = 0
j = 0
# [1] Walk both lists with one index each. Each list is sorted and has no overlaps inside it.
while i < len(first) and j < len(second):
# [2] The shared part starts at the later start and ends at the earlier end.
low = max(first[i][0], second[j][0])
high = min(first[i][1], second[j][1])
# [3] If low is at most high, the two slots share at least one slot number: record the shared part.
if low <= high:
result.append([low, high])
# [4] Drop the slot that ends first. It cannot meet anything later in the other list.
if first[i][1] < second[j][1]:
i += 1
else:
j += 1
return resultpublic int[][] sharedSlots(int[][] first, int[][] second) {
List<int[]> result = new ArrayList<>();
int i = 0;
int j = 0;
// [1] Walk both lists with one index each. Each list is sorted and has no overlaps inside it.
while (i < first.length && j < second.length) {
// [2] The shared part starts at the later start and ends at the earlier end.
int low = Math.max(first[i][0], second[j][0]);
int high = Math.min(first[i][1], second[j][1]);
// [3] If low is at most high, the two slots share at least one slot number: record the shared part.
if (low <= high) {
result.add(new int[] {low, high});
}
// [4] Drop the slot that ends first. It cannot meet anything later in the other list.
if (first[i][1] < second[j][1]) {
i++;
} else {
j++;
}
}
return result.toArray(new int[0][]);
}vector<vector<int>> sharedSlots(const vector<vector<int>>& first, const vector<vector<int>>& second) {
vector<vector<int>> result;
size_t i = 0;
size_t j = 0;
// [1] Walk both lists with one index each. Each list is sorted and has no overlaps inside it.
while (i < first.size() && j < second.size()) {
// [2] The shared part starts at the later start and ends at the earlier end.
int low = max(first[i][0], second[j][0]);
int high = min(first[i][1], second[j][1]);
// [3] If low is at most high, the two slots share at least one slot number: record the shared part.
if (low <= high) {
result.push_back({low, high});
}
// [4] Drop the slot that ends first. It cannot meet anything later in the other list.
if (first[i][1] < second[j][1]) {
i++;
} else {
j++;
}
}
return result;
}function sharedSlots(first, second) {
const result = [];
let i = 0;
let j = 0;
// [1] Walk both lists with one index each. Each list is sorted and has no overlaps inside it.
while (i < first.length && j < second.length) {
// [2] The shared part starts at the later start and ends at the earlier end.
const low = Math.max(first[i][0], second[j][0]);
const high = Math.min(first[i][1], second[j][1]);
// [3] If low is at most high, the two slots share at least one slot number: record the shared part.
if (low <= high) {
result.push([low, high]);
}
// [4] Drop the slot that ends first. It cannot meet anything later in the other list.
if (first[i][1] < second[j][1]) {
i++;
} else {
j++;
}
}
return result;
}This version scans the list in the order it arrives. It compares each event with the open block, as the template does, but it skips the sort.
This version sets the block's end to the end of the new event, not to the larger end.
This version joins only when the later start is less than the earlier end. With slot numbers, that misses events that share exactly one slot.
This version sorts the events by time and puts a start before an end at the same time. A room that frees at minute 5 then looks busy at minute 5.
The app lets a user keep as many events as possible, and no two kept events may overlap. Take [1, 10], [2, 3] and [4, 5]. Sorting by start keeps [1, 10] first, and nothing else fits: 1 event. Sorting by end keeps [2, 3] and [4, 5]: 2 events.
systemdesignmastery.dev/dsa/cheatsheets/intervals