← Questions

Fewest intervals to remove so one covers the rest

0
AmazonCodingLast asked Jul 2025

A coding interview question asked in Amazon's technical phone screen, last asked Jul 2025. It tests intervals and sorting.

You get n closed intervals [l, r] on a number line. Remove as few as possible so that one of the remaining intervals covers all the others: there is a remaining [L, R] with L <= l and r <= R for every remaining [l, r]. Return the number of intervals removed.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • min_removals(intervals: list[list[int]]) -> int — the covering interval must be one of the kept intervals, and an interval covers itself.

Example

[[1, 10], [2, 3], [4, 5], [6, 7]]                    ->  0   # [1, 10] covers the rest
[[1, 2], [3, 4], [5, 6]]                             ->  2   # disjoint: keep one
[[1, 5], [2, 3], [4, 8], [5, 6], [0, 2], [5, 7]]     ->  3   # keep [4, 8], [5, 6], [5, 7]

Constraints

  • 0 <= n <= 10^5; l <= r; endpoints may be large.
  • Intervals can be equal, nested or disjoint.

Clarifying questions

  • Must the cover be one of the remaining intervals, or any interval?
  • Are endpoints inclusive? Do touching intervals count as contained?
  • How should exact duplicates count?
  • What is the answer for an empty list?

What a strong answer covers

  • The reduction: fewest removals = n minus the most intervals one container can hold. For a fixed [L, R], it holds every interval with l >= L and r <= R.
  • The O(n^2) check of every container, then a faster count: sort by l descending, insert right ends into a Fenwick tree over compressed values, and query how many have r <= R. O(n log n).
  • Ties on l: insert every interval with the same l before querying any of them, so duplicates and the container itself are counted.
  • Tests: duplicates, point intervals, one interval, empty.

Follow-ups

  • Return which intervals to remove.
  • The cover may be any interval of length at most D, not necessarily one of the inputs.
  • Intervals arrive one by one; report the answer after each in O(log n).

Where it's asked

  • Amazon · Technical phone screen · Last asked Jul 202560 min · Live coding in a shared editor that does not run code, plus Leadership Principles questions · No AI

What it tests

intervals · sorting

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding