Simple easy to understand solution


#1
bool compareInterval(Interval a, Interval b){
     return (a.start < b.start);
 }
vector<Interval> Solution::merge(vector<Interval> &A) {
sort(A.begin(),A.end(),compareInterval);
    vector<Interval> res;
    for(int i = 0; i < A.size()-1; i++){
        if(A[i].end >= A[i+1].start){
            A[i+1].start = A[i].start;
            A[i+1].end = max(A[i+1].end, A[i].end);
        }
        else res.push_back(A[i]);
    }
    res.push_back(A[A.size()-1]);
    return res;
    
}

Thanks to @ankit-kumar_596 for the sort hint.


#2

what is the use of last pushback statement?


#3

We are iterating only up to i=A.size()-2 , so the last Interval present does not get pushed back into the vector. Hence the last push_back is required.