<p>Given an array <code>intervals</code> where <code>intervals[i] = [l<sub>i</sub>, r<sub>i</sub>]</code> represent the interval <code>[l<sub>i</sub>, r<sub>i</sub>)</code>, remove all intervals that are covered by another interval in the list.</p>

<p>The interval <code>[a, b)</code> is covered by the interval <code>[c, d)</code> if and only if <code>c &lt;= a</code> and <code>b &lt;= d</code>.</p>

<p>Return <em>the number of remaining intervals</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> intervals = [[1,4],[3,6],[2,8]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> Interval [3,6] is covered by [2,8], therefore it is removed.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> intervals = [[1,4],[2,3]]
<strong>Output:</strong> 1
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= intervals.length &lt;= 1000</code></li>
	<li><code>intervals[i].length == 2</code></li>
	<li><code>0 &lt;= l<sub>i</sub> &lt; r<sub>i</sub> &lt;= 10<sup>5</sup></code></li>
	<li>All the given intervals are <strong>unique</strong>.</li>
</ul>

class Solution {
public:
    int removeCoveredIntervals(vector<vector<int>>& intervals) {
        vector<vector<int>> ans;
        auto comp = [&](const vector<int>& i, const vector<int>& j) {
            if (i[0] == j[0])
                return i[1] > j[1];
            return i[0] < j[0];
        };
        sort(intervals.begin(), intervals.end(), comp);
        ans.push_back(intervals[0]);
        int k = 0;
        for (int i = 1; i < intervals.size(); ++i) {
            if ((intervals[i][0] >= ans.back()[0]) and
                (intervals[i][1] <= ans.back()[1])) {
                // Scenario 1: Completely covered suppose existing interval in
                // vector is [1, 8] and this ith interval is [2, 6] , this is
                // completely inside i.e. start and end lies inside , hence this
                // interval is surely removed, count this.
                ++k;
            } else if (intervals[i][0] > ans.back()[1]) {
                // Scenario 2: Suppose vector has [1, 8]  and ith interval is
                // [9, 10] , totallly unrelated, so push this interval in vector
                // as this is going to be used next time.
                ans.push_back(intervals[i]);
            } else if ((intervals[i][0] > ans.back()[0]) and
                       (intervals[i][0] <= ans.back()[1]))
                // Scenario 3: vector has [1, 8] and ith interval is  [5, 10],
                // so take maximum of both end point.
                ans.back()[1] = max(ans.back()[1], intervals[i][1]);
        }
        return intervals.size() - k;
    }
};
15100