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 C++
prefix[0] = [1];
Attempts:
3 left
💡 Hint
Common Mistakes
Using prefix[1] instead of arr[0]
Initializing prefix[0] to 0 instead of arr[0]
✗ Incorrect
The prefix sum array starts with the first element of the input array, so prefix[0] = arr[0].
2fill in blank
mediumComplete the code to compute the prefix sum for the current index i.
DSA C++
prefix[i] = prefix[i - 1] [1] arr[i];
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-' instead of '+'
Using '*' or '/' which are incorrect for 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 loop condition to correctly iterate over the array indices.
DSA C++
for (int i = 1; i [1] n; i++) {
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' causes out of bounds access
Using '>' or '>=' causes the loop to never run
✗ Incorrect
The loop should run while i is less than n to avoid going out of bounds.
4fill in blank
hardFill both blanks to create a function that returns the sum of elements from index l to r using the prefix sum array.
DSA C++
int rangeSum(int l, int r, const vector<int>& prefix) {
if (l == 0) return prefix[[1]];
return prefix[[2]] - prefix[l - 1];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using prefix[l] instead of prefix[r]
Using prefix[r+1] which is out of bounds
✗ Incorrect
To get sum from l to r, return prefix[r] - prefix[l-1], and if l is 0, return prefix[r].
5fill in blank
hardFill all three blanks to build a prefix sum array from input vector arr.
DSA C++
vector<int> prefixSum(const vector<int>& arr) {
int n = arr.size();
vector<int> prefix(n);
prefix[0] = [1];
for (int i = 1; i [2] n; i++) {
prefix[i] = prefix[i - 1] [3] arr[i];
}
return prefix;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '-' instead of '+' in sum
Loop condition using '<=' causing out of bounds
Initializing prefix[0] incorrectly
✗ Incorrect
Initialize prefix[0] with arr[0], loop while i < n, and add prefix[i-1] and arr[i].
