Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Remove every interval that is covered by another interval ([a, b] is covered by [c, d] if c ≤ a and b ≤ d); count those that remain.

Problem: Remove every interval that is covered by another interval ([a, b] is covered by [c, d] if c ≤ a and b ≤ d); count those that remain.
def remaining(iv):
    iv.sort(key=lambda x: (x[0], -x[1])); cnt = 0; end = -1
    for s, e in iv:
        if e > end: cnt += 1; end = e
    return cnt
print(remaining([[1, 4], [3, 6], [2, 8], [1, 8], [9, 10], [9, 9]]))
What is printed?
  1. A. 2
  2. B. 4
  3. C. 3
  4. D. 5

Correct answer: A. 2

Sorting by start ascending and end descending puts a covering interval before the ones it covers. [1,8] covers [1,4], [2,8] and [3,6]; [9,10] covers [9,9]. Remaining: [1,8] and [9,10] → 2.

More Coding Interview Problems questions

Exams that ask this topic