Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to sort intervals by their end time.
DSA C++
sort(intervals.begin(), intervals.end(), [](auto &a, auto &b) { return a.end [1] b.end; });Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' will sort in descending order, which is not helpful here.
Using '==' or '!=' will not sort properly.
✗ Incorrect
Sorting intervals by their end time in ascending order helps to select intervals that finish earliest, minimizing removals.
2fill in blank
mediumComplete the code to check if the current interval overlaps with the last selected interval.
DSA C++
if (intervals[i].start [1] prev_end) { count++; } else { prev_end = intervals[i].end; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>=' or '>' reverses the logic and causes wrong overlap detection.
Using '>' misses cases where intervals touch at endpoints.
✗ Incorrect
If the current interval starts before the previous interval ends (start < prev_end), it overlaps. Using '<' checks for overlap.
3fill in blank
hardFix the error in the loop that iterates over intervals starting from the second element.
DSA C++
for (int i = [1]; i < intervals.size(); i++) { /* logic */ }
Attempts:
3 left
💡 Hint
Common Mistakes
Starting at 0 causes double counting the first interval.
Starting at intervals.size() - 1 or 2 skips necessary intervals.
✗ Incorrect
We start from the second interval (index 1) because the first interval is always selected initially.
4fill in blank
hardFill both blanks to update the count of removals and the end time of the last selected interval.
DSA C++
if (intervals[i].start [1] prev_end) { [2]++; } else { prev_end = intervals[i].end; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' reverses overlap logic.
Incrementing wrong variable name causes errors.
✗ Incorrect
If current interval starts before previous end, it overlaps, so increment count of removals.
5fill in blank
hardFill all three blanks to complete the function that returns the minimum number of intervals to remove.
DSA C++
int eraseOverlapIntervals(vector<Interval>& intervals) {
if (intervals.empty()) return 0;
sort(intervals.begin(), intervals.end(), [](auto &a, auto &b) { return a.end [1] b.end; });
int count = 0;
int prev_end = intervals[0].end;
for (int i = [2]; i < intervals.size(); i++) {
if (intervals[i].start [3] prev_end) {
count++;
} else {
prev_end = intervals[i].end;
}
}
return count;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' in sort or overlap check reverses logic.
Starting loop at 0 causes double counting.
✗ Incorrect
Sort by end ascending ('<'), start loop at 1, and check if current start < prev_end to detect overlap.
