A. prefix array is not initialized with 0 at index 0
B. Loop runs one time too many
C. arr[i] is accessed out of bounds
D. prefix array is declared with wrong type
Solution
Step 1: Check prefix array initialization
The prefix array is empty initially, so prefix[0] is undefined.
Step 2: Identify impact on prefix sum calculation
prefix[i] is undefined for i=0, so prefix[1] = undefined + arr[0] results in NaN.
Final Answer:
prefix array is not initialized with 0 at index 0 -> Option A
Quick Check:
Initialize prefix[0] = 0 to avoid NaN [OK]
Hint: Always start prefix array with 0 at index 0 [OK]
Common Mistakes:
Not initializing prefix[0]
Assuming empty array has prefix[0]
Ignoring NaN results
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 sums, then sum = prefix[5] - prefix[1]
B. Calculate prefix sums, then sum = prefix[6] - prefix[1]
C. Calculate prefix sums, then sum = prefix[5] - prefix[2]
D. Calculate prefix sums, then sum = prefix[6] - prefix[2]
Solution
Step 1: Understand prefix sum indexing
Prefix sum array prefix has prefix[0] = 0, prefix[i] = sum of arr[0] to arr[i-1].
Step 2: Calculate sum from index 2 to 5
Sum = prefix[6] - prefix[2], because prefix[6] sums arr[0..5], prefix[2] sums arr[0..1].
Final Answer:
Calculate prefix sums, then sum = prefix[6] - prefix[2] -> Option D
Quick Check:
Sum of arr[2..5] = prefix[6] - prefix[2] [OK]
Hint: Sum(i to j) = prefix[j+1] - prefix[i] [OK]
Common Mistakes:
Off-by-one errors in prefix indices
Subtracting wrong prefix sums
Confusing inclusive/exclusive ranges
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.