<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:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
           sort(intervals.begin(),intervals.end());
       int n=intervals.size();
       int flag=0;
       vector<vector<int>>ans;
       for(int i=0;i<n-1;i++){
        auto it=intervals[i];
        auto p=intervals[i+1];
        if(it[0]<p[0] && it[1]<p[0]) ans.push_back(it);
        else if((it[0]<p[0] && it[1]>=p[0]) || (it[0]<=p[1] && it[1]>p[1]) || (it[0]>=p[0] && it[1]<=p[1])){
            int l=min(it[0],p[0]);
            int r=max(it[1],p[1]);
            if(i+1==n-1) flag=1;
            i++;
            while(i+1<n){
                auto q=intervals[i+1];
                if((q[0]<l && q[1]>=l)||(q[0]<=r && q[1]>r)||(q[0]>=l && q[1]<=r)){
                    l=min(l,q[0]);
                    r=max(r,q[1]);
                    if(i+1==n-1) flag=1;
                    i++;
                }else break;
            }
            ans.push_back({l,r});
        }
       else{
        ans.push_back(it);
       } 
       }
       if(flag==0){
        ans.push_back(intervals[n-1]);
       }
       return ans;
    //     sort(intervals.begin(),intervals.end());
    //     vector<vector<int>>ans;
    //     int n=intervals.size();
    //     for(int i=0;i<n;i++){
    //         if(ans.empty()|| ans.back()[1]<intervals[i][0]) ans.push_back(intervals[i]);
    //         else ans.back()[1]=max(ans.back()[1],intervals[i][1]);
    //     }
    //     return ans;
    }
};
24500