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?- A. 8
- B. 11
- C. 5
- 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
- Problem: What does this Python snippet print? def add(x, bucket=[]): bucket.append(x) return len(bucket) add(1); add(2) print(add(3))
- Problem: What does this Python snippet print? g = [[0]3]3 g[1][2] = 7 print(sum(map(sum, g)))
- Problem: What does this Python snippet print? print(-7 // 2, -7 % 3, 7 // -2)
- Problem: What does this snippet print? gen = (xx for x in range(4)) print(sum(gen), sum(gen))
- Problem: What does this snippet print? fs=[lambda: i for i in range(3)] print([f() for f in fs])
- Problem: What does this snippet print? s = "abcdefgh" print(s[::-3], s[5:1:-2])