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

Problem: n = 10⁵ intervals; for each, count how many other intervals it overlaps. What is the best complexity?

  1. A. O(n log n): sort starts and ends; overlapping count = n − 1 − (intervals ending before its start) − (intervals starting after its end), each found by binary search
  2. B. O(n²) – each pair must be checked
  3. C. O(n) – a single pass over unsorted intervals
  4. D. O(n log² n) – a 2-D segment tree is required

Correct answer: A. O(n log n): sort starts and ends; overlapping count = n − 1 − (intervals ending before its start) − (intervals starting after its end), each found by binary search

Two intervals do NOT overlap only if one ends before the other starts, and those two cases are disjoint, so subtract both counts. Two sorted arrays and two binary searches per interval give O(n log n).

More Coding Interview Problems questions

Exams that ask this topic