<p>Given an array&nbsp;of <code>intervals</code>&nbsp;where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, merge all overlapping intervals, and return <em>an array of the non-overlapping intervals that cover all the intervals in the input</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> intervals = [[1,3],[2,6],[8,10],[15,18]]
<strong>Output:</strong> [[1,6],[8,10],[15,18]]
<strong>Explanation:</strong> Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> intervals = [[1,4],[4,5]]
<strong>Output:</strong> [[1,5]]
<strong>Explanation:</strong> Intervals [1,4] and [4,5] are considered overlapping.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= intervals.length &lt;= 10<sup>4</sup></code></li>
	<li><code>intervals[i].length == 2</code></li>
	<li><code>0 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>4</sup></code></li>
</ul>

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        intervals.sort() # sort by start, then end
        merge_start, merge_end = intervals[0]
        res = list()
        
        for i in range(1, len(intervals)):
            curr_start, curr_end = intervals[i]

            # notice that the current interval can only either overlap with the merge interval,
            # or come completely after the merge interval
            # there's no case where the curr interval comes before the merge interval, because we've the intervals are sorted by (start, end)
            # so the curr start must be >= merge start since we see curr after whichever intervals that were used to create merge interval

            # curr interval overlaps with the merge interval
            if curr_start <= merge_end and curr_end >= merge_start:
                # notice how we don't have to update merge_start
                # because merge_start must already be <= curr_start
                merge_end = max(merge_end, curr_end)
            else: # curr interval comes after merge interval                
                res.append([merge_start, merge_end])
                merge_start, merge_end = curr_start, curr_end

        res.append([merge_start, merge_end])

        return res


    # def merge(self, intervals: List[List[int]]) -> List[List[int]]:
    #     intervals.sort()
    #     res = [intervals[0]]

    #     for interval in intervals:
    #         if interval[0] > res[-1][1]:
    #             res.append(interval)             
    #         else:
    #             # subtle detail: we don't have to update the whole tuple
    #             # because the previous start must already be equal or smaller than curr start                
    #             res[-1][1] = max(res[-1][1], interval[1])

    #     return res
21000