Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: Insert a new interval into a sorted list of non-overlapping intervals, merging if necessary.

Problem: Insert a new interval into a sorted list of non-overlapping intervals, merging if necessary.
def insert(iv, new):
    out, i, n = [], 0, len(iv)
    while i < n and iv[i][1] < new[0]:
        out.append(iv[i]); i += 1
    while i < n and iv[i][0] <= new[1]:
        new = [min(new[0], iv[i][0]), max(new[1], iv[i][1])]; i += 1
    return out + [new] + iv[i:]
print(insert([[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], [4, 8]))
What is printed?
  1. A. [[1, 2], [3, 8], [12, 16]]
  2. B. [[1, 2], [3, 10], [12, 16]]
  3. C. [[1, 2], [4, 10], [12, 16]]
  4. D. [[1, 2], [3, 5], [4, 8], [6, 7], [8, 10], [12, 16]]

Correct answer: B. [[1, 2], [3, 10], [12, 16]]

Three phases: copy intervals ending before the new start, absorb every interval starting at or before the new end, copy the rest. [4,8] absorbs [3,5], [6,7], [8,10] (8 ≤ 8 touches) → [3,10]. O(n).

More Coding Interview Problems questions

Exams that ask this topic