Question presented to candidate: "You are given a list of intervals, each a list [start, end], in no particular order. Write a Python function that merges all overlapping intervals and returns the merged list sorted by start."
What a strong answer should cover:
- Sort by start, then one pass that either extends the last merged interval or starts a new one.
- Use
max(last_end, end)when extending, because an interval can be nested inside the previous one. - Complexity: O(n log n) for the sort plus O(n) for the pass; O(n) for the output.
- Touching intervals ([1, 4] and [4, 5]):
<=merges them; confirm the expected behaviour. - Python details:
sorted(..., key=lambda iv: iv[0])returns a new list whilelist.sort()mutates the caller's list; append a new[start, end]so mutatingmerged[-1]never changes the input.
Clarifying questions expected:
- Do touching intervals count as overlapping?
- May I modify the input list?
Code / implementation expected: Yes โ a function merge(intervals) -> list[list[int]] in Python 3.