sagelearnai

Intervals

Signal: the input is a list of [start, end] pairs (meetings, bookings, ranges, balloons), with questions about overlap, merging, inserting, removing the fewest to avoid conflicts, or counting simultaneous ones.

Core idea: sort, then sweep left to right, comparing each interval with the last one you kept. After sorting by start, two intervals [a, b] and [c, d] (with a ≤ c) overlap iff c ≤ b.

0246810 [1, 4] [3, 6] [8, 10] merged [1, 6] [8, 10]

Which sort key?

GoalSort byWhy
Merge overlapping / insertstartOverlaps become adjacent
Keep the max number of non-overlapping intervals (or min removals, min arrows)endFinishing earliest leaves the most room (classic greedy proof)
Max simultaneous intervals (rooms needed)separate starts and ends, or a min-heap of end timesSweep line over events
python
intervals.sort(key=lambda x: x[0])
merged = []
for s, e in intervals:
    if merged and s <= merged[-1][1]:       # overlaps the last kept interval
        merged[-1][1] = max(merged[-1][1], e)
    else:
        merged.append([s, e])
Clarify the boundary

Do [1, 4] and [4, 6] overlap? Problems differ (touching meetings usually don't conflict, but touching ranges usually merge). Ask, and use < vs <= accordingly.

Problems

  1. Insert Interval (Medium): Copy left part, merge the overlapping middle, copy right part
  2. Merge Intervals (Medium): Sort by start; extend or append
  3. Non-overlapping Intervals (Medium): Greedy: keep the interval that ends first
  4. Meeting Rooms (Easy): Sort by start; any overlap between neighbors means no
  5. Meeting Rooms II (Medium): Sweep line: sorted starts vs sorted ends (or a min-heap of end times)
  6. Minimum Number of Arrows to Burst Balloons (Medium): Sort by end; shoot at the end of the first unburst balloon
  7. Car Pooling (Medium): Difference array over locations: +p at pickup, −p at drop-off; prefix sum ≤ capacity
  8. Minimum Interval to Include Each Query (Hard): Offline: sort queries; add intervals with start ≤ q to a heap keyed by size; pop those ending < q
  9. Summary Ranges (Easy): Extend a run while next == prev + 1; emit "a->b" or "a"
  10. Interval List Intersections (Medium): Two pointers; overlap = [max starts, min ends]; advance whichever ends first
  11. My Calendar I (Medium): Half-open intervals overlap iff s1 < e2 and s2 < e1; keep a sorted list and check neighbors
  12. Remove Covered Intervals (Medium): Sort by start asc, end desc; count intervals that extend the max end
  13. Data Stream as Disjoint Intervals (Hard): Sorted disjoint intervals; on insert, find the neighbors by binary search and merge
  14. My Calendar II (Medium): Keep bookings and their pairwise overlaps; reject if the new event hits an existing overlap