Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern

Problem: Merge overlapping booking intervals.

Problem: Merge overlapping booking intervals.
def merge(iv):
    iv.sort(); out = []
    for s, e in iv:
        if out and s <= out[-1][1]:
            out[-1][1] = max(out[-1][1], e)
        else:
            out.append([s, e])
    return out
print(merge([[8, 10], [1, 3], [2, 6], [15, 18], [6, 7], [17, 20]]))
What is printed?
  1. A. [[1, 7], [8, 10], [15, 20]]
  2. B. [[1, 6], [6, 7], [8, 10], [15, 20]]
  3. C. [[1, 7], [8, 10], [15, 18], [17, 20]]
  4. D. [[1, 3], [2, 7], [8, 10], [15, 20]]

Correct answer: A. [[1, 7], [8, 10], [15, 20]]

Sort by start, then extend the last interval while the next one starts at or before its end. [1,3]+[2,6]+[6,7] touch at 6 → [1,7]; [15,18]+[17,20] → [15,20]. Using max(end, e) matters when an interval is nested. O(n log n).

More Coding Interview Problems questions

Exams that ask this topic