Skip to the page

Linear patterns · mid

Sorting and intervals

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; the comparator and the stability of the 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 add it. O(n log n).
  • Overlap test for half-open intervals [s, e): a.start < b.end and b.start < a.end. Back-to-back meetings (10-11, 11-12) do not overlap.
  • Max overlap or meeting rooms: sort starts and ends; walk both; when an end <= the current start, free a room. Or use events (+1 at start, -1 at end) sorted so that ends come before starts at the same time.
  • Multi-key sort: compare key 1, and only if equal compare key 2. A stable sort keeps the earlier order for ties, so sorting by key 2 and then by key 1 also works. Python's sort and Java's sort of objects are stable; C++ std::sort is not (use std::stable_sort).
  • Comparators: Java Comparator.comparingInt or Integer.compare (do not return a - b, it can overflow); Python key=; C++ a lambda that returns a < b with a strict order (never <=, it can crash).
  • Strings compare by character code by default, so 'B' comes before 'a'; for 'file2' before 'file10' you need a natural-order comparison.
  • Do not change the caller's array by accident: Java Arrays.sort and Python list.sort() work in place; Python sorted() and a copy in the other languages leave the input alone.

The red pen

Common traps: mistake → fix

  • Mistake: Intervals touching at the end overlap

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

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

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

  • Mistake: A comparator written as (a, b)

    Fix: a - b is always right -> it overflows for very large or very negative values; use Integer.compare.

  • Mistake: A C++ comparator with <= is fine

    Fix: it breaks the strict weak order rule and can crash the sort.

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 and drop points?
  4. Lay out overlapping events side by side in a 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