Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to insert the new interval into the list.
DSA C++
intervals.insert(intervals.begin() + [1], newInterval);Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 or intervals.size() blindly without finding the correct position.
Using an undefined variable like pos.
✗ Incorrect
We insert the new interval at position i, where i is the index found to place the new interval.
2fill in blank
mediumComplete the code to find the correct position to insert the new interval.
DSA C++
while (i < intervals.size() && intervals[i].end < newInterval.start) { [1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Decrementing i which causes an infinite loop.
Trying to increment the interval or newInterval values.
✗ Incorrect
We increment i to move forward until we find the right position where the new interval can be inserted.
3fill in blank
hardFix the error in the merging loop condition.
DSA C++
while (i < intervals.size() && intervals[i].start <= [1]) { newInterval.start = std::min(newInterval.start, intervals[i].start); newInterval.end = std::max(newInterval.end, intervals[i].end); intervals.erase(intervals.begin() + i); }
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing with newInterval.start instead of newInterval.end.
Comparing with intervals[i].end which is incorrect here.
✗ Incorrect
We merge intervals that start before or at the end of the new interval, so we compare intervals[i].start with newInterval.end.
4fill in blank
hardFill both blanks to correctly merge overlapping intervals.
DSA C++
newInterval.start = std::min(newInterval.start, intervals[[1]].start); newInterval.end = std::max(newInterval.end, intervals[[2]].end);
Attempts:
3 left
💡 Hint
Common Mistakes
Using different indices for start and end.
Using fixed indices like 0 or intervals.size() - 1.
✗ Incorrect
We use the current index i to update the start and end of newInterval during merging.
5fill in blank
hardFill all three blanks to complete the function that inserts and merges intervals.
DSA C++
int i = 0; while (i < intervals.size() && intervals[i].end < [1]) { i++; } intervals.insert(intervals.begin() + i, [2]); while (i + 1 < intervals.size() && intervals[i + 1].start <= [3]) { intervals[i].start = std::min(intervals[i].start, intervals[i + 1].start); intervals[i].end = std::max(intervals[i].end, intervals[i + 1].end); intervals.erase(intervals.begin() + i + 1); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong interval boundaries for comparison.
Inserting wrong object or at wrong position.
✗ Incorrect
We find the position where newInterval.start fits, insert newInterval, then merge overlapping intervals by comparing with intervals[i].end.
