Typorithm · medium

Merge Meeting Times

merge-meetingsproblem-labintervalssortingsweep
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Merge Meeting Times

0%

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.

01

Sort intervals by start time first.

02

Overlap means current.start <= last.end.

03

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
}

Read the implementation

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

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)

2. Last merged block

Only the most recently merged block can overlap the next interval once sorted.

const last = merged[merged.length - 1]

3. Detect overlap

An interval overlaps when its start falls at or before the previous block's end.

if (current.start <= last.end) {

4. Extend the block

Math.max stretches the block to cover the further end of the two overlapping intervals.

last.end = Math.max(last.end, current.end)

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.

Merge Meeting Times: Lesson & Practice · Typorithm | ApplyDjinn