Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to sort intervals by their start value.
DSA Rust
intervals.sort_by_key(|interval| interval.[1]);Attempts:
3 left
💡 Hint
Common Mistakes
Sorting by end instead of start causes incorrect merging order.
Using a non-existent field like 'length' or 'value'.
✗ Incorrect
We sort intervals by their start value to process them in order.
2fill in blank
mediumComplete the code to check if two intervals overlap.
DSA Rust
if intervals[i].start <= merged.last().unwrap().[1] {
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing with 'start' instead of 'end' of last merged interval.
Using incorrect field names.
✗ Incorrect
Two 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 Rust
merged.last_mut().unwrap().end = merged.last().unwrap().end.[1](intervals[i].end);Attempts:
3 left
💡 Hint
Common Mistakes
Using 'min' causes incorrect merging by shortening intervals.
Using 'sum' or 'abs' is not meaningful here.
✗ Incorrect
We update the end to the maximum to cover the full merged interval.
4fill in blank
hardFill both blanks to complete the loop that merges intervals.
DSA Rust
for i in [1]..intervals.len() { if intervals[i].start <= merged.last().unwrap().[2] {
Attempts:
3 left
💡 Hint
Common Mistakes
Starting loop from 0 causes comparing interval with itself.
Comparing with 'start' instead of 'end' causes wrong overlap detection.
✗ Incorrect
Loop starts from 1 to compare with previous intervals; compare current start with last merged end.
5fill in blank
hardFill all three blanks to complete the merging function.
DSA Rust
fn merge_intervals(mut intervals: Vec<Interval>) -> Vec<Interval> {
intervals.sort_by_key(|interval| interval.[1]);
let mut merged = vec![intervals[[2]].clone()];
for i in [3]..intervals.len() {
if intervals[i].start <= merged.last().unwrap().end {
let last = merged.last_mut().unwrap();
last.end = last.end.max(intervals[i].end);
} else {
merged.push(intervals[i].clone());
}
}
merged
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'end' instead of 'start' for sorting.
Starting merged with wrong index.
Looping from 0 instead of 1.
✗ Incorrect
Sort by start, initialize merged with first interval (index 0), loop from second interval (index 1).
