A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 435. Non-overlapping Intervals, the solution in this repository is mainly a greedy solution.
Guide
What?
The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: greedy.
The notes already sitting in the source point us in the right direction:
- Greedy, maintain the shortest intervals
Guide
When?
This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are eraseOverlapIntervals.
Guide
Why?
The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.
- Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
- A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
- A set is doing the membership or uniqueness work, which keeps the main loop readable.
- The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
Guide
How?
Walk through the solution in this order:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- Check which value survives to the return statement.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Greedy, maintain the shortest intervals
02/*
03the algorithm is not optimal!
04consider [[-3,3],[4,8]] and [2,5],
05this algorithm will choose [2,5],
06which is sub-optimal!
07*/
08//WA
09//15 / 18 test cases passed.
10class Solution {
11public:
12 int eraseOverlapIntervals(vector<vector<int>>& intervals) {
13 set<int> points;
14
15 int n = intervals.size();
16
17 for(int i = 0; i < n; ++i){
18 points.insert(intervals[i][0]);
19 points.insert(intervals[i][1]);
20 }
21
22 unordered_map<int, int> shrink;
23
24 auto it = points.begin();
25 for(int i = 0; i < points.size(); ++i, ++it){
26 shrink[*it] = i;
27 }
28
29 for(vector<int>& interval : intervals){
30 interval[0] = shrink[interval[0]];
31 interval[1] = shrink[interval[1]];
32 }
33
34 sort(intervals.begin(), intervals.end(),
35 [](vector<int>& a, vector<int>& b){
36 return (a[1]-a[0] == b[1]-b[0]) ? a[0] < b[0]: a[1]-a[0] < b[1]-b[0];
37 });
38
39 unordered_set<int> used;
40
41 int discarded = 0;
42
43 for(int i = 0; i < n; ++i){
44 bool overlapping = false;
45 for(int p = intervals[i][0]; p < intervals[i][1]; ++p){
46 if(used.find(p) != used.end()){
47 overlapping = true;
48 break;
49 }
50 }
51 if(!overlapping){
52 for(int p = intervals[i][0]; p < intervals[i][1]; ++p){
53 used.insert(p);
54 }
55 }else{
56 ++discarded;
57 }
58 }
59
60 return discarded;
61 }
62};
63
64//Greedy, maintain the intervals with minimum right boundary
65//proof: https://en.wikipedia.org/wiki/Interval_scheduling#Interval_Scheduling_Maximization
66//http://lonati.di.unimi.it/algo/0910/lab/kowalski6.pdf
67//https://leetcode.com/problems/non-overlapping-intervals/discuss/91713/Java%3A-Least-is-Most
68//Runtime: 40 ms, faster than 59.83% of C++ online submissions for Non-overlapping Intervals.
69//Memory Usage: 10.7 MB, less than 32.78% of C++ online submissions for Non-overlapping Intervals.
70//time: O(NlogN)
71class Solution {
72public:
73 int eraseOverlapIntervals(vector<vector<int>>& intervals) {
74 int n = intervals.size();
75
76 sort(intervals.begin(), intervals.end(),
77 [](vector<int>& a, vector<int>& b){
78 return a[1] < b[1];
79 });
80
81 int discarded = 0;
82 int last_end = INT_MIN;
83
84 for(vector<int> interval : intervals){
85 if(last_end > interval[0])
86 ++discarded;
87 else
88 last_end = interval[1];
89 }
90
91 return discarded;
92 }
93};
Cost