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 Java
int[] prefixSum = new int[arr.length]; prefixSum[0] = arr[1];
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses or curly braces instead of square brackets for array indexing.
✗ Incorrect
In Java, to access the first element of an array, use square brackets with index 0: arr[0].
2fill in blank
mediumComplete the for loop header to iterate from the second element to the end of the array.
DSA Java
for (int i = [1]; i < arr.length; i++) { prefixSum[i] = prefixSum[i - 1] + arr[i]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Starting the loop at 0 which causes incorrect prefix sums.
Starting at 2 which skips the second element.
✗ Incorrect
The prefix sum starts from the second element, so the loop index i should start at 1.
3fill in blank
hardFix the error in the prefix sum calculation inside the loop.
DSA Java
prefixSum[i] = prefixSum[i [1] 1] + arr[i];
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' instead of '-' causing runtime errors.
Using '*' or '/' which are incorrect for indexing.
✗ Incorrect
To get the previous prefix sum, subtract 1 from i: prefixSum[i - 1].
4fill in blank
hardFill both blanks to complete the method that returns the sum of elements between indices left and right (inclusive) using the prefix sum array.
DSA Java
public int rangeSum(int left, int right) {
if (left == 0) {
return prefixSum[1];
} else {
return prefixSum[right] [2] prefixSum[left - 1];
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using prefixSum[left] instead of prefixSum[right] in the first return.
Using addition instead of subtraction in the else return.
✗ Incorrect
If left is 0, return prefixSum[right]. Otherwise, subtract prefixSum[left - 1] from prefixSum[right] to get the sum.
5fill in blank
hardFill all three blanks to complete the method that builds the prefix sum array from the input array.
DSA Java
public int[] buildPrefixSum(int[] arr) {
int[] prefixSum = new int[arr.length];
prefixSum[0] = arr[1];
for (int i = [2]; i < arr.length; i++) {
prefixSum[i] = prefixSum[i [3] 1] + arr[i];
}
return prefixSum;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of square brackets for array access.
Starting loop at 0 causing incorrect sums.
Using '+' instead of '-' in prefixSum index.
✗ Incorrect
Access first element with arr[0], start loop at 1, and subtract 1 to get previous prefix sum index.
