# 56 Merge Intervals

Given a collection of intervals, merge all overlapping intervals.

For example,\
Given`[1,3],[2,6],[8,10],[15,18]`,\
return`[1,6],[8,10],[15,18]`.

**The Idea:** We can sort the intervals by start time, the intervals would fall under one of three cases which are illustrated below. In the first case, there are no updates. In the second case, the interval end updates, and in the third case, we add the previous interval and update the current interval.

![](/files/-LoJIpfpVdXnY0gwn3Kq)

**Complexity:** O(nlogn + n) time and O(1) space

```python
class Interval:
    def __init__(self, s=0, e=0):
        self.start = s
        self.end = e


class Solution:
    def merge(self, intervals):
        """
        :type intervals: List[Interval]
        :rtype: List[Interval]
        """

        if not intervals:
            return []

        intervals.sort(key=lambda i: i.start)
        merged_intervals = []

        cur_start = intervals[0].start
        cur_end = intervals[0].end
        for i, interval in enumerate(intervals[1:], 1):
            if cur_start <= interval.start <= cur_end and \
                                    cur_start <= interval.end <= cur_end:
                continue
            if cur_start <= interval.start <= cur_end:
                cur_end = interval.end
            else:
                merged_intervals.append(Interval(cur_start, cur_end))
                cur_start = interval.start
                cur_end = interval.end
        merged_intervals.append(Interval(cur_start, cur_end))

        return merged_intervals


def print_intervals(intervals):
    for i in intervals:
        print('(', i.start, i. end, ')', end='')
    print('\n')

obj = Solution()
print_intervals(obj.merge([Interval(1, 4), Interval(2, 3)]))  # ( 1 4 )
print_intervals(obj.merge([]))  # ( )
print_intervals(obj.merge([Interval(5, 10)]))  # ( 5 10 )
print_intervals(obj.merge([Interval(1, 3), Interval(2, 10), Interval(8, 15)]))  # ( 1 15 )
print_intervals(obj.merge([Interval(1, 3), Interval(2, 6), Interval(8, 10), Interval(15, 18)]))  # ( 1 6 )( 8 10 )( 15 18 )
print_intervals(obj.merge([Interval(1, 3), Interval(4, 6), Interval(7, 10)]))  # ( 1 3 )( 4 6 )( 7 10 )
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/56-merge-intervals.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
