Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to sort intervals by their start time.
DSA Java
Arrays.sort(intervals, (a, b) -> a[[1]] - b[[1]]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using index 1 instead of 0 causes sorting by end time, which is incorrect.
Using 'length' or 2 causes index out of bounds errors.
✗ Incorrect
We sort intervals by their start time, which is at index 0 in each interval array.
2fill in blank
mediumComplete the code to check if two intervals overlap.
DSA Java
if (intervals[i][0] <= merged.get(merged.size() - 1)[[1]]) {
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing start with start instead of end misses overlaps.
Using index 0 instead of 1 causes wrong comparisons.
✗ Incorrect
We check if the current interval's start is less than or equal to the last merged interval's end, which is at index 1.
3fill in blank
hardFix the error in updating the end time of the last merged interval.
DSA Java
merged.get(merged.size() - 1)[1] = Math.max(merged.get(merged.size() - 1)[1], intervals[i][[1]]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using index 0 updates start time incorrectly.
Using index 2 or length causes index errors.
✗ Incorrect
We update the end time at index 1 by taking the maximum of current end and new interval's end at index 1.
4fill in blank
hardFill both blanks to add a new interval to merged list and convert list to array.
DSA Java
merged.add(new int[] {intervals[i][[1]], intervals[i][[2]]});
return merged.toArray(new int[[3]][]);Attempts:
3 left
💡 Hint
Common Mistakes
Swapping start and end indices.
Using intervals.length instead of merged.size() for array size.
✗ Incorrect
We add the current interval's start (index 0) and end (index 1). Then convert merged list to array with size merged.size().
5fill in blank
hardFill all three blanks to complete the merge intervals method.
DSA Java
public int[][] merge(int[][] intervals) {
if (intervals.length == 0) return new int[0][];
Arrays.sort(intervals, (a, b) -> a[[1]] - b[[1]]);
List<int[]> merged = new ArrayList<>();
merged.add(intervals[0]);
for (int i = 1; i < intervals.length; i++) {
if (intervals[i][0] <= merged.get(merged.size() - 1)[[2]]) {
merged.get(merged.size() - 1)[1] = Math.max(merged.get(merged.size() - 1)[1], intervals[i][1]);
} else {
merged.add(intervals[i]);
}
}
return merged.toArray(new int[[3]][]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong indices for start or end.
Using intervals.length instead of merged.size() for array size.
✗ Incorrect
Sort by start (index 0), check overlap with last merged end (index 1), and convert list to array with merged.size().
