AlgoInsight

DSA problem

Non-overlapping Intervals

MediumIntervalsPattern: Intervalstop75FreeAmazonGoogleMicrosoftFacebookBloomberg

Given an array of intervals intervals where intervals[i] = [start_i, end_i], return the minimum number of intervals you need to remove so that the remaining intervals are non-overlapping. Two intervals [a, b] and [c, d] overlap if a < d and c < b; touching at a single endpoint (e.g. [1, 2] and [2, 3]) does NOT count as overlapping.

This is a classical interval scheduling problem: maximize the number of mutually non-overlapping intervals that can be kept, then subtract from n. The greedy algorithm that solves the kept-count is to sort by end time and always pick the interval with the earliest end that does not overlap the previously picked one.

Why earliest end? Among compatible candidates, the one ending earliest leaves the most room for future intervals. Any other choice ends later, so any compatible interval found after a non-greedy choice would also have been compatible with the greedy choice. By induction the greedy schedule is at least as large as any other valid schedule.

The implementation sorts by end ascending, then sweeps. Track prevEnd, initialized to negative infinity (or the end of the first interval after counting it). For each interval, if its start is at least prevEnd, keep it and update prevEnd. Count kept intervals; the answer to the problem is n - kept. Sorting dominates at O(n log n) time with O(1) auxiliary space.

Examples

Example 1
Input: intervals = [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: After sorting by end: [[1,2],[2,3],[1,3],[3,4]]. Keep [1,2] (prevEnd=2). [2,3] start=2 >= 2, keep (prevEnd=3). [1,3] start=1 < 3, skip. [3,4] start=3 >= 3, keep. Kept=3, removed=4-3=1.
Example 2
Input: intervals = [[1,2],[1,2],[1,2]]
Output: 2
Explanation: All three identical intervals overlap pairwise; only one can stay so two must be removed.
Example 3
Input: intervals = [[1,2],[2,3]]
Output: 0
Explanation: The intervals touch at point 2 but do not overlap by the problem's definition, so neither needs to be removed.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

arrayintervalsgreedysorting

Browse all DSA problems