Data Structures & AlgorithmsHardTCS NQT · Product Company OA

Problem: What is the total length covered by the union of the intervals [1, 3], [2, 6] and [8, 10]? Run the code.

Problem: What is the total length covered by the union of the intervals [1, 3], [2, 6] and [8, 10]? Run the code.
iv = sorted([(1, 3), (2, 6), (8, 10)])
total = 0
cs, ce = iv[0]
for s, e in iv[1:]:
    if s <= ce:
        ce = max(ce, e)
    else:
        total += ce - cs
        cs, ce = s, e
total += ce - cs
print(total)
What is printed?
  1. A. 8
  2. B. 11
  3. C. 5
  4. D. 7

Correct answer: D. 7

Sorting and merging: [1, 3] and [2, 6] overlap and become [1, 6] (length 5), and [8, 10] adds 2, so the union has length 7. Summing the lengths without merging gives 8, also counting integer points (e − s + 1) per interval gives 3 + 5 + 3 = 11, and forgetting the final total += after the loop drops the last block (5).

More Coding Interview Problems questions

Exams that ask this topic