Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to sort intervals by their end time.
DSA Javascript
intervals.sort((a, b) => [1]);Attempts:
3 left
💡 Hint
Common Mistakes
Sorting by start time instead of end time.
Using incorrect subtraction order.
Returning 0 which means no sorting.
✗ Incorrect
Sorting intervals by their end time helps to greedily select intervals that finish earliest, minimizing overlaps.
2fill in blank
mediumComplete the code to check if the current interval overlaps with the last selected interval.
DSA Javascript
if (intervals[i].start < intervals[1].end) {
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing with the current interval itself.
Using i + 1 which is the next interval.
Using 0 which is the first interval always.
✗ Incorrect
We compare the start of the current interval with the end of the last selected interval to detect overlap.
3fill in blank
hardFix the error in updating the end time of the last selected interval to the minimum end time.
DSA Javascript
intervals[1].end = Math.min(intervals[i].end, intervals[2].end);
Attempts:
3 left
💡 Hint
Common Mistakes
Updating the current interval instead of the last selected.
Using i + 1 which is out of range or next interval.
Using 0 which is the first interval always.
✗ Incorrect
We update the end time of the last selected interval to the minimum of its current end and the current interval's end to keep intervals non-overlapping.
4fill in blank
hardFill both blanks to correctly count removals and update the last selected interval index.
DSA Javascript
if (intervals[i].start < intervals[1].end) { removals[2]; } else { last = i; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using post-increment removals++ which may cause subtle bugs.
Decreasing removals instead of increasing.
Using wrong index instead of last.
✗ Incorrect
We check overlap with the last selected interval and increase removals count using prefix increment. If no overlap, update last to current index.
5fill in blank
hardFill all three blanks to complete the function that returns minimum removals for non-overlapping intervals.
DSA Javascript
function eraseOverlapIntervals(intervals) {
if (intervals.length === 0) return 0;
intervals.sort((a, b) => [1]);
let removals = 0;
let last = 0;
for (let i = 1; i < intervals.length; i++) {
if (intervals[i].start < intervals[2].end) {
removals[3];
intervals[last].end = Math.min(intervals[i].end, intervals[last].end);
} else {
last = i;
}
}
return removals;
}Attempts:
3 left
💡 Hint
Common Mistakes
Sorting by start instead of end.
Using wrong index for overlap check.
Using post-increment instead of prefix increment.
✗ Incorrect
Sort by end time, check overlap with last selected interval, increment removals if overlap, update last interval end to minimum, else update last index.
