Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the minimum number of intervals to remove so that the rest are non-overlapping – implemented with sort by START and keeping the smaller end on conflict.

Problem: Find the minimum number of intervals to remove so that the rest are non-overlapping – implemented with sort by START and keeping the smaller end on conflict.
def remove_min(iv):
    iv.sort(); removed = 0; end = float('-inf')
    for s, e in iv:
        if s < end:
            removed += 1; end = min(end, e)
        else:
            end = e
    return removed
print(remove_min([[1, 100], [11, 22], [1, 11], [2, 12]]), remove_min([[0, 2], [1, 3], [2, 4], [3, 5], [4, 6]]))
What is printed?
  1. A. 3 2
  2. B. 2 3
  3. C. 2 2
  4. D. 1 2

Correct answer: C. 2 2

Sorting by start also works if, on every conflict, you drop the interval with the larger end (keep min end). [1,11], [1,100], [2,12], [11,22]: drop [1,100] and [2,12] → 2. The chain [0,2], [2,4], [4,6] survives; [1,3] and [3,5] go. O(n log n).

More Coding Interview Problems questions

Exams that ask this topic