Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to insert the new interval into the list.
DSA Javascript
function insertInterval(intervals, newInterval) {
let result = [];
let i = 0;
while (i < intervals.length && intervals[i][1] < newInterval[[1]]) {
result.push(intervals[i]);
i++;
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using newInterval[1] instead of newInterval[0] causes wrong comparisons.
Comparing intervals[i][0] instead of intervals[i][1].
✗ Incorrect
We compare the end of intervals[i] with the start of newInterval, which is at index 0.
2fill in blank
mediumComplete the code to merge overlapping intervals with the new interval.
DSA Javascript
while (i < intervals.length && intervals[i][0] <= newInterval[[1]]) { newInterval[0] = Math.min(newInterval[0], intervals[i][0]); newInterval[1] = Math.max(newInterval[1], intervals[i][[2]]); i++; }
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up indices for start and end of intervals.
Using newInterval[0] instead of newInterval[1] in the while condition.
✗ Incorrect
We merge intervals where intervals[i][0] <= newInterval[1]. We update newInterval[1] with the max end, which is intervals[i][1].
3fill in blank
hardFix the error in adding the merged newInterval to the result list.
DSA Javascript
result.[1](newInterval);Attempts:
3 left
💡 Hint
Common Mistakes
Using append() which is not a JavaScript array method.
Using add() or insert() which do not exist on arrays.
✗ Incorrect
In JavaScript, arrays use push() to add elements at the end.
4fill in blank
hardFill both blanks to add the remaining intervals after merging.
DSA Javascript
while (i [1] intervals.length) { result.[2](intervals[i]); i++; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using <= causes index out of range error.
Using append() which is not a JavaScript array method.
✗ Incorrect
We loop while i is less than intervals.length and use push() to add elements to the result.
5fill in blank
hardFill all three blanks to complete the insertInterval function.
DSA Javascript
function insertInterval(intervals, newInterval) {
let result = [];
let i = 0;
while (i < intervals.length && intervals[i][1] < newInterval[[1]]) {
result.push(intervals[i]);
i++;
}
while (i < intervals.length && intervals[i][0] <= newInterval[[2]]) {
newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
newInterval[1] = Math.max(newInterval[1], intervals[i][[3]]);
i++;
}
result.push(newInterval);
while (i < intervals.length) {
result.push(intervals[i]);
i++;
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Swapping start and end indices.
Using wrong indices in comparisons causing incorrect merges.
✗ Incorrect
We compare intervals[i][1] with newInterval[0] in the first loop, then intervals[i][0] with newInterval[1] in the second. We update newInterval[1] with intervals[i][1].
