InterviewSam
Tech TracksStudySystem DesignAptitudeDaily Quiz
Log inStart free
Tech TracksStudySystem DesignAptitudeDaily Quiz
All topics

Intervals

Sort by start or end, then sweep: merging, inserting, meeting rooms.

5 pages, free to read

Start studying
  1. 1

    Interval basics & overlap

    Beginner

    An interval is a [start, end] range, and two intervals overlap exactly when each one starts before the other ends: a.start <= b.end and b.start <= a.end.

    8 min read
  2. 2

    Merging intervals

    Intermediate

    Sort intervals by start, then sweep once: each interval either extends the last merged block or starts a new one, for O(n log n) total.

    8 min read
  3. 3

    Inserting an interval

    Intermediate

    To insert a new interval into a sorted, disjoint list, copy everything that ends before it, absorb everything that overlaps it, then copy the rest: one pass, O(n).

    8 min read
  4. 4

    Meeting rooms & the sweep line

    Intermediate

    To find how many intervals are active at once, turn each interval into a +1 start event and a -1 end event, sort the events, and sweep while keeping a running count; the peak is the answer.

    10 min read
  5. 5

    Interval scheduling

    Intermediate

    To keep the most non-overlapping intervals, sort by end time and greedily take each interval that starts after the last one you took; earliest finish leaves the most room for the rest.

    10 min read