Hint: Subtract prefix sums to get subarray sum [OK]
Common Mistakes:
Confusing indices and subtracting wrong prefix values
Adding prefix sums instead of subtracting
Forgetting prefix sums start at index 0
4. Consider the following code snippet to build a prefix sum array. Identify the error:
int[] prefix = new int[arr.Length];
prefix[0] = 0;
for(int i = 1; i < arr.Length; i++) {
prefix[i] = prefix[i-1] + arr[i];
}
medium
A. Loop should start from i = 0, not 1
B. prefix[0] should be arr[0], not 0
C. Array prefix should have length arr.Length + 1
D. No error, code is correct
Solution
Step 1: Check initialization of prefix[0]
Setting prefix[0] = 0 is incorrect; it should be arr[0] to start cumulative sum correctly.
Step 2: Verify loop and array length
The loop starting at 1 and array length are fine; only prefix[0] initialization is wrong.
Final Answer:
prefix[0] should be arr[0], not 0 -> Option B
Quick Check:
Correct prefix start = arr[0] [OK]
Hint: Initialize prefix[0] with arr[0], not zero [OK]
Common Mistakes:
Starting loop at 0 causing index errors
Using wrong prefix array size
Assuming zero initialization is always correct
5. You have an integer array arr of length 6: {3, 1, 4, 1, 5, 9}. You want to find the sum of elements from index 2 to 5 inclusive using a prefix sum array prefix where prefix[i] stores sum of elements from index 0 to i. Which expression correctly computes this sum?
hard
A. prefix[5] - prefix[1]
B. prefix[5] - prefix[2]
C. prefix[4] - prefix[1]
D. prefix[5] + prefix[1]
Solution
Step 1: Understand prefix sum indexing
prefix[i] = sum of arr[0] to arr[i]. To get sum from index 2 to 5, subtract prefix[1] (sum up to index 1) from prefix[5].
Step 2: Write the correct expression
Sum = prefix[5] - prefix[1]
Final Answer:
prefix[5] - prefix[1] -> Option A
Quick Check:
Sum(2 to 5) = prefix[5] - prefix[1] [OK]
Hint: Sum(i to j) = prefix[j] - prefix[i-1] [OK]
Common Mistakes:
Subtracting prefix[i] instead of prefix[i-1]
Adding prefix sums instead of subtracting
Using wrong indices for prefix array
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.