Leetcode 57 Solution

This article provides solution to leetcode question 57 (insert-interval)

https://leetcode.com/problems/insert-interval

Solution

/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
class Solution {
public:
    vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
        int start = INT_MAX;
        int end = INT_MIN;
        int i = 0;

        for (i = 0; i < intervals.size(); i++)
        {
            if (newInterval.end < intervals[i].start)
                break;
            else if (newInterval.start <= intervals[i].end)
            {
                newInterval.start = min(newInterval.start, intervals[i].start);
                newInterval.end = max(newInterval.end, intervals[i].end);
                start = min(start, i);
                end = i;
            }
        }

        if (start != INT_MAX)
        {
            intervals.erase(intervals.begin() + start, intervals.begin() + end + 1);
            intervals.insert(intervals.begin() + start, newInterval);
        }
        else
            intervals.insert(intervals.begin() + i, newInterval);

        return intervals;
    }
};