Coding Medium Software Engineer Backend Full Stack

Given a collection of intervals, merge all overlapping intervals (Merge Intervals).

Practise this question with AI feedback

Record your spoken answer or type your response to receive immediate scoring and STAR improvements.

💡 Suggested Approach & Sample Answer

Optimal Sorting Approach & Code:
- Sort intervals by start time so overlapping candidates are adjacent, then merge in a single linear pass.

def merge_intervals(intervals: list[list[int]]) -> list[list[int]]:
    if not intervals:
        return []
    intervals.sort(key=lambda x: x[0])
    merged = [intervals[0]]
    for current in intervals[1:]:
        prev = merged[-1]
        if current[0] <= prev[1]:
            prev[1] = max(prev[1], current[1])
        else:
            merged.append(current)
    return merged

Complexity & Key Logic:
- Time Complexity: O(N log N) dominated by sorting the N intervals.
- Space Complexity: O(N) to store the merged output list.
- Algorithm Details:
- Sorting by start time guarantees that if current.start <= prev.end, an overlap exists.
- Merge by extending prev.end = max(prev.end, current.end) to handle completely contained intervals.
- If no overlap exists (current.start > prev.end), append current as a new disjoint interval.

🎯 What Interviewers Listen For

How would you answer this in a real interview?

Use our free AI mock practice tool to test your response, analyze speaking pacing, and refine your STAR structure.

🔗 Related Coding Questions