Skip to the page

Linear patterns · mid

Sorting and intervals in JavaScript

Sort intervals by start, then one pass merges overlaps, and sorting start and end times separately (a sweep line) tells how many overlap at once; in JavaScript the comparator and the stable sort decide correctness.

The notes

What you must know

  • Merge intervals: sort by start; if next.start <= last.end, extend last.end = max(last.end, next.end); else push. O(n log n).
  • Overlap test for half-open intervals [s, e): a.start < b.end && b.start < a.end. Back-to-back meetings (10–11, 11–12) do not overlap.
  • Max overlap / meeting rooms: sort starts and ends; walk both; when an end <= current start, free a room. Or events (+1 at start, −1 at end) sorted with ends before starts at the same time.
  • Multi-key sort: compare key 1, and only if equal compare key 2. Stable sort (ES2019) keeps the earlier order for ties, so sorting by key 2 then key 1 also works.
  • Strings: localeCompare (with { numeric: true } for 'file2' < 'file10'); default sort compares code units ('B' < 'a').
  • Never mutate the caller's array by accident: sort() is in place; use toSorted() or a copy.

The red pen

Common traps: mistake → fix

  • Mistake: Intervals touching at the end overlap

    Fix: decide open vs closed ends with the interviewer; for calendars use [start, end).

  • Mistake: Sorting by start alone fixes 'meeting rooms'

    Fix: you also need to track the earliest end (sorted ends or a min-heap).

  • Mistake: Sorting mutates only a local copy

    Fix: sort() changes the original array; props or state get mutated in React.

  • Mistake: sort((a, b) => a.start > b.start) works

    Fix: it returns true or false, never a negative number, so the order is wrong; return a.start - b.start.

Easy to hard

Questions interviewers ask, easy to hard

  1. Merge overlapping intervals.
  2. Can a person attend all meetings? How many rooms are needed?
  3. Car pooling: is capacity ever exceeded? What happens at equal pickup/drop points?
  4. Lay out overlapping events side by side in a calendar day view.

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview