Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to sort intervals by their start time.
DSA C++
sort(intervals.begin(), intervals.end(), [](const vector<int>& a, const vector<int>& b) {
return a[[1]] < b[[2]];
});Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong index for sorting.
Comparing with 'a' or other variables instead of indices.
✗ Incorrect
We sort intervals by their start time, which is at index 0 in each interval vector.
2fill in blank
mediumComplete the code to check if current interval overlaps with the last merged interval.
DSA C++
if (intervals[i][0] [1] merged.back()[1]) { merged.back()[1] = max(merged.back()[1], intervals[i][1]); } else { merged.push_back(intervals[i]); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '<=' misses touching intervals.
Using '>' or '>=' reverses the logic.
✗ Incorrect
Intervals overlap if the current start is less than or equal to the last merged end.
3fill in blank
hardFix the error in updating the end of the last merged interval.
DSA C++
merged.back()[1] = [1](merged.back()[1], intervals[i][1]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using min() shrinks the interval incorrectly.
Using abs() or sum() causes wrong results or errors.
✗ Incorrect
We update the end to the maximum of the two ends to cover the full merged interval.
4fill in blank
hardFill both blanks to complete the loop that merges intervals.
DSA C++
for (int [1] = 1; [1] < intervals.size(); [2]++) { if (intervals[i][0] <= merged.back()[1]) { merged.back()[1] = max(merged.back()[1], intervals[i][1]); } else { merged.push_back(intervals[i]); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names in initialization and increment.
Using variables not declared or inconsistent.
✗ Incorrect
The loop variable is 'i' used consistently for indexing intervals.
5fill in blank
hardFill all three blanks to create a map of interval starts to their lengths for intervals longer than 2.
DSA C++
map<int, int> intervalLengths = {
{interval[[1]], interval[[2]] - interval[[3]]}
for (const auto& interval : intervals) if (interval[1] - interval[0] > 2)
};Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up start and end indices.
Using wrong indices for subtraction.
✗ Incorrect
Start is at index 0, end at index 1, length is end - start.
