Merge Intervals

class Solution {
public:
    vector<vector<int>> merge(vector<vector<int>>& a) {
        sort(a.begin(), a.end());
        int i=0;
        while(i<a.size()-1){
            if(a[i][1]>=a[i+1][0] && a[i][1]<=a[i+1][1]){
                a[i+1][1] = max(a[i][1], a[i+1][1]);
                a[i+1][0] = a[i][0];
                a.erase(a.begin()+i);
            }else if(a[i][1]>a[i+1][1]){
                a.erase(a.begin()+i+1);
            }else i++;
        }
        return a;
    }
};

I don’t know why this isn’t working. Any test case or corner case ?

Since “vector.erase” takes linear time your solution is O(N^2), other than that it seems fine.
You can try to store answer in a separate vector rather than modifying the original vector.

1 Like

I think that’s why I was getting TLE.
Thanks :smiley: