<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 {
public:
    int min(int a, int b) {
        return a < b ? a : b;
    }
    int max(int a, int b) {
        return a < b ? b : a;
    }

    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        if (intervals.empty()) {
            return vector<vector<int>>();
        }
        vector<vector<int>> final_interval;
        sort(intervals.begin(), intervals.end(), [](
            const vector<int>& a, const vector<int>& b
            ) {
                return a[0] < b[0]; 
            });
        final_interval.push_back(intervals[0]);

        for (int i = 1; i < intervals.size(); ++i) {
            vector<int> latest_interval = final_interval[final_interval.size() - 1];
            vector<int> current_interval = intervals[i];

            if (latest_interval[1] >= current_interval[0]) {
                vector<int> merged_interval = {
                    min(latest_interval[0], current_interval[0]),
                    max(latest_interval[1], current_interval[1])
                };
                final_interval.pop_back();
                final_interval.push_back(merged_interval);
            } else {
                final_interval.push_back(current_interval);
            }
        }
        return final_interval;
    }
        
};

26100