Intervals · Pattern 1 of 3

Interval basics: overlap, merge, intersect and greedy

Sort by start, then compare each interval with the last one you kept: extend it if they overlap, start a new one if not. Sort by end instead when you want to keep as many intervals as possible.

5 variations · 10 problems · 7 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Merge overlapping ranges, or insert one into a sorted list
  • Can one person attend every meeting? Does a new booking clash?
  • The fewest removals (or arrows) so that nothing overlaps
  • The common part of two lists of ranges

The template

Basics
// merge overlapping intervals: sort by start, extend the last kept one
int[][] merge(int[][] intervals) {
    Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
    List<int[]> res = new ArrayList<>();
    for (int[] cur : intervals) {
        int[] last = res.isEmpty() ? null : res.get(res.size() - 1);
        if (last != null && cur[0] <= last[1]) last[1] = Math.max(last[1], cur[1]);  // overlaps: extend
        else res.add(new int[]{cur[0], cur[1]});                                  // gap: new interval
    }
    return res.toArray(new int[0][]);
}

// fewest removals so the rest do not overlap: greedily keep the one that ends first
int eraseOverlapIntervals(int[][] intervals) {
    Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1]));
    int kept = 0;
    long end = Long.MIN_VALUE;
    for (int[] iv : intervals) {
        if (iv[0] >= end) { kept++; end = iv[1]; }   // touching is allowed here
    }
    return intervals.length - kept;
}

The variations

  1. 1Merge overlapping intervals

    Sort by start and keep a result list. If the next interval starts at or before the last kept end, extend that end with max; otherwise push it. Inserting into an already sorted list needs no sort: copy what ends before, merge what overlaps, copy the rest. Partition labels is a merge too: each letter spans from its first to its last position.

  2. 2Intersect two sorted lists

    Two pointers, one per list. The common part of the two current intervals is [max(starts), min(ends)] when that is not empty. Then move the pointer whose interval ends first, because it cannot meet anything else.

  3. 3Detect a conflict

    After sorting by start, there is a clash exactly when some interval starts before the previous one ends. For bookings that arrive one at a time, check the new one against the booking just before it and just after it (a sorted map makes that O(log n)).

    Now you solve
  4. 4Greedy by end time

    To keep the most intervals that do not overlap, always keep the one that ends first: it leaves the most room for the rest. Removals are n minus what you kept. The fewest arrows for balloons is the same count, with closed intervals.

  5. 5Best pair that does not overlap

    Sort by start and walk forward. Keep a min-heap of earlier events by end time; pop every event that ended before the current start and remember the best value among them. Current value plus that best is a candidate answer.

Mistakes to avoid

  • Merging without sorting first: [[2, 6], [1, 3]] then merges into [2, 6] and loses the part from 1 to 2 (sorted, the answer is [1, 6]).
  • Greedy removal sorted by start: one long interval that starts early blocks many short ones. Sort by end.
  • Balloons use closed intervals (an arrow at x = 2 bursts [1, 2] and [2, 3]), unlike non-overlapping intervals where touching is fine. Check > vs >=.
Next: Line sweep: count what overlaps at every moment →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.