Challenge - 5 Problems
Prefix Sum Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of Prefix Sum Array Construction
What is the output of the prefix sum array after running the following code?
DSA C
int arr[] = {2, 4, 6, 8}; int n = 4; int prefix[n]; prefix[0] = arr[0]; for(int i = 1; i < n; i++) { prefix[i] = prefix[i-1] + arr[i]; } for(int i = 0; i < n; i++) { printf("%d ", prefix[i]); }
Attempts:
2 left
💡 Hint
Remember prefix sum at index i is sum of all elements from 0 to i.
✗ Incorrect
The prefix sum array stores cumulative sums. Starting with 2, then 2+4=6, then 6+6=12, then 12+8=20.
🧠 Conceptual
intermediate1:30remaining
Understanding Prefix Sum Array Usage
Which of the following is the main advantage of using a prefix sum array?
Attempts:
2 left
💡 Hint
Think about how prefix sums help in range sum queries.
✗ Incorrect
Prefix sums let you find sum of elements between two indices quickly by subtracting prefix sums.
🔧 Debug
advanced2:00remaining
Identify the Error in Prefix Sum Calculation
What error will this code produce when calculating prefix sums?
DSA C
int arr[] = {1, 3, 5}; int n = 3; int prefix[n]; for(int i = 0; i <= n; i++) { if(i == 0) prefix[i] = arr[i]; else prefix[i] = prefix[i-1] + arr[i]; } for(int i = 0; i < n; i++) { printf("%d ", prefix[i]); }
Attempts:
2 left
💡 Hint
Check the loop condition carefully for array indexing.
✗ Incorrect
The loop runs from i=0 to i=3 (inclusive), but array indices go only up to 2, causing out of bounds access.
🚀 Application
advanced1:30remaining
Calculate Sum of Subarray Using Prefix Sum Array
Given prefix sum array prefix = {3, 8, 15, 21, 28}, what is the sum of elements from index 2 to 4 (0-based)?
Attempts:
2 left
💡 Hint
Use formula: sum(l, r) = prefix[r] - prefix[l-1]
✗ Incorrect
Sum from index 2 to 4 = prefix[4] - prefix[1] = 28 - 8 = 20.
❓ Predict Output
expert2:30remaining
Output of Prefix Sum with Negative Numbers
What is the output of the prefix sum array after running this code?
DSA C
int arr[] = {5, -2, 7, -3, 4}; int n = 5; int prefix[n]; prefix[0] = arr[0]; for(int i = 1; i < n; i++) { prefix[i] = prefix[i-1] + arr[i]; } for(int i = 0; i < n; i++) { printf("%d ", prefix[i]); }
Attempts:
2 left
💡 Hint
Add each element to the sum of all previous elements.
✗ Incorrect
Prefix sums: 5, 5+(-2)=3, 3+7=10, 10+(-3)=7, 7+4=11.
