Data Structures & AlgorithmsHardProduct Company SDE · interval cover

Problem: What is the minimum number of intervals from [[1,4],[3,7],[6,10],[9,10]] needed to cover the segment [1, 10]? Run the greedy code.

Problem: What is the minimum number of intervals from [[1,4],[3,7],[6,10],[9,10]] needed to cover the segment [1, 10]? Run the greedy code.
iv = [(1, 4), (3, 7), (6, 10), (9, 10)]
start, end = 1, 10
cur = start
cnt = 0
while cur < end:
    best = max((e for s, e in iv if s <= cur), default=None)
    if best is None or best <= cur:
        cnt = -1
        break
    cur = best
    cnt += 1
print(cnt)
What is printed?
  1. A. 2
  2. B. 3
  3. C. 4
  4. D. -1

Correct answer: B. 3

Starting at 1, the best reach is 4, then 7 from [3,7], then 10 from [6,10], so three intervals are needed.

More Coding Interview Problems questions

Exams that ask this topic