THN Interview Prep

435. Non-overlapping Intervals

At a Glance

  • Topic: greedy
  • Pattern: Greedy on intervals (pick earliest ending)
  • Difficulty: Medium
  • Companies: Amazon, Google, Microsoft, Bloomberg, Apple
  • Frequency: High
  • LeetCode: 435

Problem (one-liner)

Given intervals [start, end], return the minimum number of intervals you must remove so that the rest are pairwise non-overlapping (strictly, typically end_i <= start_j for ordering).

Recognition Cues

  • “Minimum removals” / max non-overlap subset
  • Sort by end time ascending; greedy keep interval if its start ≥ last kept end
  • Classic “activity selection”

Diagram

At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.

Loading diagram…

Approaches

  • DPO(n²) time.
  • Greedy by earliest finishO(n log n) time / O(1) extra (besides sort). <- pick this in interview.

Optimal Solution

Go

package main

import "sort"

func eraseOverlapIntervals(intervals [][]int) int {
	if len(intervals) <= 1 {
		return 0
	}
	sort.Slice(intervals, func(left int, right int) bool {
		return intervals[left][1] < intervals[right][1]
	})
	kept := 0
	lastEnd := intervals[0][1]
	for index := 1; index < len(intervals); index++ {
		start := intervals[index][0]
		end := intervals[index][1]
		if start >= lastEnd {
			kept++
			lastEnd = end
		}
	}
	return len(intervals) - (kept + 1)
}

JavaScript

function eraseOverlapIntervals(intervals) {
	if (intervals.length <= 1) return 0;
	const sorted = [...intervals].sort((left, right) => left[1] - right[1]);
	let kept = 0;
	let lastEnd = sorted[0][1];
	for (let index = 1; index < sorted.length; index++) {
		const [start, end] = sorted[index];
		if (start >= lastEnd) {
			kept++;
			lastEnd = end;
		}
	}
	return intervals.length - (kept + 1);
}

Walkthrough

Sort by end; sweep choosing greedily compatible intervals. Remove count = total − maximum compatible subset size.

Invariant: among intervals ending earliest, keeping the one with smallest end preserves maximum future room.

Edge Cases

  • Empty list → 0
  • All disjoint → 0 removals
  • All overlap at a point → boundaries matter per definition (<= vs <)

Pitfalls

  • Sorting by start instead of end breaks greedy proof
  • Confusing max intervals kept vs removals needed

Similar Problems

Variants

  • Weighted interval scheduling → DP by end time.

Mind-Map Tags

#intervals #greedy #activity-selection #medium

Last updated on

Spotted something unclear or wrong on this page?

On this page