1. Sort by start
Sorting by start time lines the intervals up so overlaps sit next to each other.
sort((a, b) => a.start - b.start)Typorithm · medium
Step 1 of 8 · intro card
Data Challenges
To merge overlapping meeting ranges, sort by start time, then sweep once: if the next interval starts at or before the last block's end, extend that block with Math.max; otherwise start a new block. Sorting guarantees a single linear pass suffices.
The scenario: you have meeting time ranges that may overlap and want them consolidated into the fewest non-overlapping blocks.
Sort the intervals by start time. Now any interval that overlaps an earlier one must overlap the most recently kept block, because everything before it started no later.
Sweep through once: if the current interval starts at or before the last block's end, extend that block to Math.max of the two ends; otherwise it is disjoint, so push it as a new block.
Sort intervals by start time first.
Overlap means current.start <= last.end.
Extend with Math.max, else push a new block.
function mergeMeetings(meetings) {
const sorted = [...meetings].sort((a, b) => a.start - b.start)
const merged = [sorted[0]]
for (let i = 1; i < sorted.length; i++) {
const current = sorted[i]
const last = merged[merged.length - 1]
if (current.start <= last.end) {
last.end = Math.max(last.end, current.end)
} else {
merged.push(current)
}
}
return merged
}Connect each part of the code to the concept before you type.
Sorting by start time lines the intervals up so overlaps sit next to each other.
sort((a, b) => a.start - b.start)Only the most recently merged block can overlap the next interval once sorted.
const last = merged[merged.length - 1]An interval overlaps when its start falls at or before the previous block's end.
if (current.start <= last.end) {Math.max stretches the block to cover the further end of the two overlapping intervals.
last.end = Math.max(last.end, current.end)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.