# Merge Overlapping Time Ranges

> Intervals piling up. Clean the timeline.

Canonical URL: <https://datadriven.io/problems/merge_overlapping_time_ranges>

Domain: Python · Difficulty: medium · Seniority: L5

## Problem

Given a list of [start, end] intervals, merge overlapping ones and return the merged list sorted by start ascending.

## Worked solution and explanation

### Why this problem exists in real interviews

This is the interval merging problem with tuple inputs. It tests the same **sort-then-scan** pattern but with tuples instead of lists, checking whether you handle immutable types and the merge logic identically.

---

### Break down the requirements

#### Step 1: Sort intervals by start time

Sorting brings overlapping intervals together for a single left-to-right pass.

#### Step 2: Merge overlapping or adjacent ranges

If the current interval's start is within the previous interval's range, extend the end. Otherwise, start a new merged interval.

#### Step 3: Return sorted non-overlapping intervals

The output should be a list of tuples in ascending start order.

---

### The solution

**Sort-and-merge with tuple output**

```python
def merge_intervals(intervals):
    if not intervals:
        return []
    sorted_ivs = sorted(intervals, key=lambda x: x[0])
    merged = [list(sorted_ivs[0])]
    for i in range(1, len(sorted_ivs)):
        current = sorted_ivs[i]
        last = merged[-1]
        if current[0] <= last[1]:
            if current[1] > last[1]:
                last[1] = current[1]
        else:
            merged.append(list(current))
    result = []
    for m in merged:
        result.append(tuple(m))
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(n log n) for sorting. The merge scan is O(n).
> 
> **Space:** O(n) for the sorted copy and the result list.

> **Interviewers Watch For**
>
> Correct handling of tuples, which are immutable. You must convert to lists for in-place modification during merging, then convert back if the output requires tuples.

> **Common Pitfall**
>
> Trying to modify a tuple element directly. `merged[-1][1] = new_end` fails on tuples. Convert to a mutable type first.

---

## Common follow-up questions

- What if the input intervals have open and closed boundaries? _(Tests tracking boundary type and adjusting the overlap condition accordingly.)_
- How would you find the gaps between merged intervals? _(Tests computing the complement: the space between consecutive merged intervals.)_
- What if you needed to merge intervals from multiple sources? _(Tests combining all intervals first, then running the merge once on the combined list.)_
- How would you determine the maximum overlap count at any point? _(Tests the sweep line algorithm with event sorting.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/merge_overlapping_time_ranges)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.