Hint: Add current element to previous prefix sum [OK]
Common Mistakes:
Confusing prefix sums with original array
Starting sums from zero incorrectly
Adding wrong elements in loop
4. Identify the error in the following code snippet that attempts to create a prefix sum array for arr of size n:
int prefix[n];
prefix[0] = 0;
for(int i = 1; i < n; i++) {
prefix[i] = prefix[i-1] + arr[i];
}
medium
A. prefix[0] should be initialized to arr[0], not 0
B. Loop should start from i = 0, not 1
C. Array prefix should be of size n+1
D. The code will cause a runtime error
Solution
Step 1: Check prefix[0] initialization
prefix[0] must hold arr[0] to start sums correctly, not zero.
Step 2: Analyze loop correctness
Loop starting at 1 is correct if prefix[0] is set properly.
Final Answer:
prefix[0] should be initialized to arr[0], not 0 -> Option A
Quick Check:
prefix[0] = arr[0] starts sums right [OK]
Hint: Initialize prefix[0] with arr[0], not zero [OK]
Common Mistakes:
Setting prefix[0] to zero causes wrong sums
Starting loop at wrong index
Assuming prefix array size must be n+1
5. You have an array arr = {3, 1, 4, 1, 5, 9, 2}. Using a prefix sum array, how would you efficiently find the sum of elements from index 2 to 5 (inclusive)?
hard
A. Calculate prefix[5] + prefix[2]
B. Sum elements from arr[2] to arr[5] directly every time
C. Use prefix[6] - prefix[2] to get the sum
D. Calculate prefix[5] - prefix[1] after building prefix sums
Solution
Step 1: Build prefix sum array
prefix[i] = sum of arr[0] to arr[i]. For example, prefix[5] = sum of arr[0..5].
Step 2: Calculate sum from index 2 to 5
Sum = prefix[5] - prefix[1], because prefix[1] = sum of arr[0..1].
Final Answer:
Calculate prefix[5] - prefix[1] after building prefix sums -> Option D
Quick Check:
Sum(i..j) = prefix[j] - prefix[i-1] [OK]
Hint: Sum subarray = prefix[end] - prefix[start-1] [OK]
Common Mistakes:
Adding prefix sums instead of subtracting
Using wrong indices for prefix subtraction
Summing elements directly ignoring prefix sums
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.