Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to sort intervals by their start time.
DSA Javascript
intervals.sort((a, b) => a[[1]] - b[[1]]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using index 1 instead of 0 causes sorting by end time, not start time.
Using 'length' or 'start' as index causes errors.
✗ Incorrect
We sort intervals by the first element (start time) which is at index 0.
2fill in blank
mediumComplete the code to check if two intervals overlap.
DSA Javascript
if (intervals[i][0] <= merged[merged.length - 1][[1]]) {
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing with index 0 (start) instead of 1 (end) causes wrong overlap detection.
Using 'length' or 'start' as index causes errors.
✗ Incorrect
We check if current interval start is less or equal to last merged interval's end (index 1).
3fill in blank
hardFix the error in updating the end of the last merged interval.
DSA Javascript
merged[merged.length - 1][1] = Math.[1](merged[merged.length - 1][1], intervals[i][1]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using Math.min causes incorrect merging by shortening intervals.
Using Math.abs or Math.round is irrelevant here.
✗ Incorrect
We update the end to the maximum of current end and new interval's end to merge properly.
4fill in blank
hardFill both blanks to correctly add a non-overlapping interval to merged list.
DSA Javascript
else { merged.[1](intervals[[2]]); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop, shift, or unshift modifies the wrong end of the array.
Using wrong index instead of i causes errors.
✗ Incorrect
We push the current interval at index i to merged when no overlap is found.
5fill in blank
hardFill all three blanks to complete the mergeIntervals function.
DSA Javascript
function mergeIntervals(intervals) {
if (intervals.length === 0) return [];
intervals.sort((a, b) => a[[1]] - b[[2]]);
const merged = [intervals[0]];
for (let [3] = 1; [3] < intervals.length; [3]++) {
if (intervals[[3]][0] <= merged[merged.length - 1][1]) {
merged[merged.length - 1][1] = Math.max(merged[merged.length - 1][1], intervals[[3]][1]);
} else {
merged.push(intervals[[3]]);
}
}
return merged;
}Attempts:
3 left
💡 Hint
Common Mistakes
Sorting by different indices causes wrong order.
Using j instead of i is allowed but inconsistent here.
Mixing indices in sort comparator causes errors.
✗ Incorrect
Sort by start index 0 for both a and b. Use i as loop variable for intervals.
