Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the prefix sum array with the first element of the input array.
DSA Rust
let mut prefix_sum = vec![0; nums.len()]; prefix_sum[0] = [1];
Attempts:
3 left
💡 Hint
Common Mistakes
Setting prefix_sum[0] to 0 instead of nums[0]
Using prefix_sum[1] before it is initialized
✗ Incorrect
The prefix sum array starts with the first element of the input array, so prefix_sum[0] should be nums[0].
2fill in blank
mediumComplete the code to calculate the prefix sum for each element starting from the second element.
DSA Rust
for i in 1..nums.len() { prefix_sum[i] = prefix_sum[i - 1] [1] nums[i]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication instead of addition
Using division which is not correct for prefix sums
✗ Incorrect
Each prefix sum is the sum of the previous prefix sum and the current element, so use +.
3fill in blank
hardFix the error in the code to correctly compute the prefix sum array.
DSA Rust
let mut prefix_sum = vec![0; nums.len()]; prefix_sum[0] = nums[0]; for i in 1..nums.len() { prefix_sum[i] = prefix_sum[i - 1] [1] nums[i]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using prefix_sum[i] instead of prefix_sum[i - 1]
Using wrong operator like - or *
✗ Incorrect
The code mistakenly uses prefix_sum[i] on the right side instead of prefix_sum[i - 1]. The blank should be + and the code should use prefix_sum[i - 1].
4fill in blank
hardFill both blanks to create a function that returns the prefix sum array for a given vector.
DSA Rust
fn prefix_sum_array(nums: &Vec<i32>) -> Vec<i32> {
let mut prefix_sum = vec![0; nums.len()];
prefix_sum[0] = nums[0];
for i in 1..nums.len() {
prefix_sum[i] = prefix_sum[i [1]] [2] nums[i];
}
prefix_sum
}Attempts:
3 left
💡 Hint
Common Mistakes
Using i+1 instead of i-1 for previous index
Using subtraction or multiplication instead of addition
✗ Incorrect
To compute prefix sums, subtract 1 from i to get the previous prefix sum index, then add the current element.
5fill in blank
hardFill all three blanks to create a function that returns the prefix sum array and handles empty input safely.
DSA Rust
fn prefix_sum_array_safe(nums: &Vec<i32>) -> Vec<i32> {
if nums.is_empty() {
return vec![];
}
let mut prefix_sum = vec![0; nums.len()];
prefix_sum[0] = nums[[1]];
for i in 1..nums.len() {
prefix_sum[i] = prefix_sum[i [2]] [3] nums[i];
}
prefix_sum
}Attempts:
3 left
💡 Hint
Common Mistakes
Using nums[1] for first element
Using i+1 instead of i-1 for previous index
Using wrong operator instead of +
✗ Incorrect
The first prefix sum is nums[0]. The loop uses i-1 for previous prefix sum index and adds the current element.
