Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new empty deque.
DSA Rust
let mut deq: std::collections::VecDeque<usize> = std::collections::VecDeque::[1]();Attempts:
3 left
š” Hint
Common Mistakes
Using `with_capacity` requires a size argument.
Using `from` expects an existing collection.
Using `default` is valid but less explicit here.
ā Incorrect
The method `new()` creates an empty VecDeque.
2fill in blank
mediumComplete the code to remove indices from the back of the deque while the current number is greater.
DSA Rust
while let Some(&back) = deq.back() { if nums[back] < nums[i] { deq.[1](); } else { break; } }
Attempts:
3 left
š” Hint
Common Mistakes
Using `pop_front()` removes from the front, which is incorrect here.
Using `push_back()` or `push_front()` adds elements instead of removing.
ā Incorrect
We remove from the back of the deque using `pop_back()` to maintain decreasing order.
3fill in blank
hardFix the error in removing indices from the front of the deque when they are out of the current window.
DSA Rust
if let Some(&front) = deq.front() { if i [1] front + k { deq.pop_front(); } }
Attempts:
3 left
š” Hint
Common Mistakes
Using `<` or `>` instead of `>=` causes incorrect removals.
Not comparing with `i - k` but with `i + k`.
ā Incorrect
We remove from front if the index is out of the window, i.e., if front <= i - k, so the operator is `>=` when rearranged.
4fill in blank
hardFill both blanks to push the current index and add the maximum to the result vector.
DSA Rust
deq.[1](i); if i + 1 >= k { result.push(nums[*deq.[2]().unwrap()].clone()); }
Attempts:
3 left
š” Hint
Common Mistakes
Using `pop_front` instead of `front` to access the max index.
Using `back` to get max index, which is incorrect.
ā Incorrect
We add the current index at the back with `push_back`, and the max is at the front of the deque accessed by `front()`.
5fill in blank
hardFill all three blanks to complete the sliding window maximum function using a deque.
DSA Rust
pub fn max_sliding_window(nums: Vec<i32>, k: usize) -> Vec<i32> {
use std::collections::VecDeque;
let mut deq: VecDeque<usize> = VecDeque::[1]();
let mut result = Vec::new();
for i in 0..nums.len() {
while let Some(&back) = deq.back() {
if nums[back] < nums[i] {
deq.[2]();
} else {
break;
}
}
deq.push_back(i);
if let Some(&front) = deq.front() {
if front + k <= i {
deq.[3]();
}
}
if i + 1 >= k {
result.push(nums[*deq.front().unwrap()]);
}
}
result
}Attempts:
3 left
š” Hint
Common Mistakes
Using `push_back` instead of `pop_back` to remove elements.
Using `pop_front` incorrectly on the back side.
Not initializing the deque properly.
ā Incorrect
We create a new deque with `new()`, remove smaller elements from back with `pop_back()`, and remove out-of-window indices from front with `pop_front()`.
