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 Typescript
const prefixSum: number[] = []; prefixSum[0] = arr[1];
Attempts:
3 left
💡 Hint
Common Mistakes
Using index 1 instead of 0 for the first element.
Trying to assign the whole array instead of a single element.
✗ Incorrect
The prefix sum array starts with the first element of the input array, so prefixSum[0] = arr[0].
2fill in blank
mediumComplete the code to calculate the prefix sum for each element starting from the second element.
DSA Typescript
for (let i = 1; i < arr.length; i++) { prefixSum[i] = prefixSum[i - 1] [1] arr[i]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication instead of addition.
Using the wrong index for prefixSum.
✗ Incorrect
Each prefix sum is the sum of the previous prefix sum and the current element.
3fill in blank
hardFix the error in the function that returns the sum of elements between two indices using the prefix sum array.
DSA Typescript
function rangeSum(prefixSum: number[], left: number, right: number): number {
if (left === 0) {
return prefixSum[right];
} else {
return prefixSum[right] [1] prefixSum[left];
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of subtraction.
Not adjusting the index for prefixSum[left - 1].
✗ Incorrect
To get the sum from left to right, subtract prefixSum[left - 1] from prefixSum[right]. The code mistakenly uses prefixSum[left], so it should subtract prefixSum[left - 1]. But since the blank is for the operator, the correct operator is '-'.
4fill in blank
hardFill both blanks to create a prefix sum array using a for loop and the addition operator.
DSA Typescript
const prefixSum: number[] = [arr[0]]; for (let i = 1; i < arr.length; i++) { prefixSum[i] = prefixSum[i [1]] [2] arr[i]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' instead of '-' for the index.
Using '-' or '*' instead of '+' for addition.
✗ Incorrect
The prefix sum at index i is the sum of prefixSum[i - 1] and arr[i]. So the first blank is '-' to get the previous index, and the second blank is '+' to add the current element.
5fill in blank
hardFill all three blanks to create a function that returns the sum of elements between two indices using prefix sums.
DSA Typescript
function rangeSum(prefixSum: number[], left: number, right: number): number {
if (left === 0) {
return prefixSum[right];
} else {
return prefixSum[right] [1] prefixSum[left [2] [3]];
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' instead of '-' for subtraction.
Using 0 instead of 1 for index adjustment.
✗ Incorrect
To get the sum from left to right, subtract prefixSum[left - 1] from prefixSum[right]. So the first blank is '-', the second blank is '-', and the third blank is '1' to get left - 1.
