NeetCode 150, stage 16: Intervals

← Greedy · All 150 problems · Math and Geometry →

An interval is a pair of numbers: a start and an end. This stage trains one habit: sort first, then make one pass. After the sort, each interval needs a comparison with only one neighbor or with the top of a heap. The choice of the sort key, start or end, is the important decision in each problem.

Garden notes: the Go syntax for this stage, Sorting.

Problems on this page

#ProblemLevelPatternTemplate
157. Insert IntervalMediumThree-phase insertB: Three-phase insert
256. Merge IntervalsMediumSort by start, then mergeA: Sort by start, then merge
3435. Non-overlapping IntervalsMediumSort by end, greedy keepC: Sort by end, then greedy keep
4252. Meeting RoomsEasySort by start, compare neighborsA: Sort by start, then merge
5253. Meeting Rooms IIMediumSweep of sorted starts and endsD: Sweep of sorted starts and ends
61851. Minimum Interval to Include Each QueryHardOffline queries, sort plus min-heapE: Offline queries with a sort and a min-heap

Templates to memorize

Template A: Sort by start, then merge

Signal

The problem says merge, overlap, “combine the ranges” or “can a person attend all the meetings”. The intervals come in any order.

// TEMPLATE A: sort by start, then compare each interval with the last one
// of the result.
func mergeOverlaps(intervals [][]int) [][]int {
    sort.Slice(intervals, func(i, j int) bool { // 1. SORT by start
        return intervals[i][0] < intervals[j][0]
    })
    res := [][]int{}
    for _, cur := range intervals {
        last := len(res) - 1
        // 2. COMPARE: cur starts before last ends
        if last >= 0 && cur[0] <= res[last][1] {
            // 3. EXTEND the last interval
            res[last][1] = max(res[last][1], cur[1])
        } else {
            // 4. APPEND: a new group starts
            res = append(res, []int{cur[0], cur[1]})
        }
    }
    return res
}

The moves are SORT, COMPARE, then EXTEND or APPEND. After the sort, an interval can overlap only the last interval of the result. Extend with max, because the current interval can be inside the last one. Read the statement for the tie: if [1,4] and [4,5] must merge, compare with <=.

Say it

“I sort by start. Then each interval either extends the last merged interval or starts a new one. The sort makes it O(n log n).”

Template B: Three-phase insert

Signal

The intervals are already sorted and do not overlap. You must add one interval and keep the two properties.

// TEMPLATE B: insert into intervals that are sorted and do not overlap. One
// pass, three phases.
func insertSorted(intervals [][]int, start, end int) [][]int {
    res := [][]int{}
    i, n := 0, len(intervals)
    // 1. BEFORE: ends before the new one starts
    for i < n && intervals[i][1] < start {
        res = append(res, intervals[i])
        i++
    }
    // 2. MERGE: starts before the new one ends
    for i < n && intervals[i][0] <= end {
        start = min(start, intervals[i][0])
        end = max(end, intervals[i][1])
        i++
    }
    res = append(res, []int{start, end})
    return append(res, intervals[i:]...) // 3. AFTER: the rest
}

The moves are BEFORE, MERGE, then AFTER. The first loop copies the intervals that end before the new one starts. The second loop grows the new interval while an interval starts at or before its end. Do not sort again: the input is sorted, so one pass gives O(n).

Say it

“The input is sorted, so I do one pass in three phases: copy what is before, merge what overlaps, copy what is after. That is O(n).”

Template C: Sort by end, then greedy keep

Signal

The problem asks for the least number of intervals to remove, or the most intervals that fit with no overlap. You choose which intervals stay.

// TEMPLATE C: sort by END, then keep each interval that starts at or after
// the last kept end.
// It returns the largest number of intervals that do not overlap.
func mostWithoutOverlap(intervals [][]int) int {
    if len(intervals) == 0 {
        return 0
    }
    sort.Slice(intervals, func(i, j int) bool { // 1. SORT by end
        return intervals[i][1] < intervals[j][1]
    })
    kept := 1
    // the first interval ends first: always keep it
    prevEnd := intervals[0][1]
    for _, cur := range intervals[1:] {
        // 2. KEEP: no overlap with the last kept interval
        if cur[0] >= prevEnd {
            kept++
            prevEnd = cur[1]
        } // 3. if not, REMOVE cur: nothing to do
    }
    return kept
}

The moves are SORT by end, KEEP, then REMOVE. The interval that ends first leaves the most room for the others, so it is always safe to keep it. A sort by start is the common mistake here. One long interval that starts first can then block many short ones.

Say it

“This is activity selection. I sort by end time and keep each interval that starts after the last kept end. The answer is n minus the number that I keep.”

Template D: Sweep of sorted starts and ends

Signal

The problem asks how many intervals are active at the same time: rooms, platforms or servers. The identity of each interval does not matter.

// TEMPLATE D: sweep. Sort the starts and the ends separately, then walk
// them in time order.
// It returns the largest number of intervals that are open at the same
// time.
func mostOpen(intervals [][]int) int {
    n := len(intervals)
    starts, ends := make([]int, n), make([]int, n)
    for i, iv := range intervals {
        starts[i], ends[i] = iv[0], iv[1]
    }
    sort.Ints(starts)
    sort.Ints(ends)
    open, most := 0, 0
    s, e := 0, 0
    for s < n {
        if starts[s] < ends[e] { // 1. START comes first: one more is open
            open++
            s++
            most = max(most, open)
        } else { // 2. END comes first (or a tie): one less is open
            open--
            e++
        }
    }
    return most
}

The moves are START and END. Two sorted slices and two indexes replace an event list. On a tie, the end goes first, so a room that becomes free at time 10 serves a meeting that starts at time 10. A min-heap of end times gives the same answer. The heap is the better tool when you must also know which room each meeting gets.

Say it

“I sort the start times and the end times separately and sweep them in order. A start adds a room and an end frees one. The peak is the answer.”

Template E: Offline queries with a sort and a min-heap

Signal

You get many query points and many intervals, and each query asks for the best interval that contains it. A scan of all the intervals for each query is too slow.

// TEMPLATE E: offline queries. Answer the queries in sorted order, so one
// sweep serves all.
// For each query point, it gives the size of the smallest interval that
// contains the point.
type span struct{ size, end int } // sizeHeap is a min-heap of span, by size
 
func smallestCover(intervals [][]int, queries []int) []int {
    sort.Slice(intervals, func(i, j int) bool { return intervals[i][0] < intervals[j][0] })
    // 1. SORT THE QUERIES: sort their indexes by value
    order := make([]int, len(queries))
    for i := range order {
        order[i] = i
    }
    sort.Slice(order, func(a, b int) bool { return queries[order[a]] < queries[order[b]] })
    res := make([]int, len(queries))
    h := sizeHeap{}
    next := 0
    for _, qi := range order {
        q := queries[qi]
        // 2. ADD: starts <= q
        for ; next < len(intervals) && intervals[next][0] <= q; next++ {
            heap.Push(&h, span{intervals[next][1] - intervals[next][0] + 1, intervals[next][1]})
        }
        for len(h) > 0 && h[0].end < q { // 3. DROP: ends before q
            heap.Pop(&h)
        }
        res[qi] = -1 // 4. ANSWER at the original index
        if len(h) > 0 {
            res[qi] = h[0].size
        }
    }
    return res
}

The moves are SORT THE QUERIES, ADD, DROP, then ANSWER. Because the queries arrive in sorted order, an interval that ends before one query also ends before all the later ones. So each interval enters the heap one time and leaves it one time. Sort a slice of indexes, not the queries, because each answer must go back to its original position. The heap type has the five methods from the Heap stage.

Say it

“I answer the queries offline, in sorted order. A min-heap by size holds the intervals that started, and I pop the ones that already ended. That gives O(n log n plus q log q).”

Mistakes in this stage

  • sort.Slice changes the slice in place. Its function gets two indexes, not two items, so compare intervals[i] with intervals[j].
  • Decide < or <= from the statement. Two meetings that touch do not overlap, but LeetCode 56 merges [1,4] and [4,5].
  • A range loop gives the same inner slice, not a copy. A write to cur[1] changes the input row.
  • A sort of the queries loses their positions. Sort a slice of indexes and write each answer at res[qi].

Solved with comments

Each problem hides its answer in three steps, so the page works as a test. Read the problem on LeetCode first. Then open the steps in order, and only as far as you need:

  1. Which pattern? Say the pattern and the template aloud. Then open step 1 to check.
  2. The idea. If you are blocked, open step 2. It has the key idea and the complexity, and no code.
  3. The Go solution. Open step 3 last. Then close it and type the solution from memory.

Each solution has the function name and the signature that LeetCode gives you. The code does not show the given types (ListNode, TreeNode, Node) or the imports. LeetCode adds the standard library imports for you. For a local file, each solution lists the imports that it needs.

57. Insert Interval

LeetCode 57 · Medium

56. Merge Intervals

LeetCode 56 · Medium

435. Non-overlapping Intervals

LeetCode 435 · Medium

252. Meeting Rooms

LeetCode 252 (premium) · free on NeetCode · Easy

253. Meeting Rooms II

LeetCode 253 (premium) · free on NeetCode · Medium

1851. Minimum Interval to Include Each Query

LeetCode 1851 · Hard


← Greedy · All 150 problems · Math and Geometry →