Challenge - 5 Problems
Prefix Sum Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this prefix sum array code?
Consider the following JavaScript code that creates a prefix sum array from an input array. What will be printed?
DSA Javascript
const arr = [2, 4, 6, 8]; const prefixSum = []; prefixSum[0] = arr[0]; for (let i = 1; i < arr.length; i++) { prefixSum[i] = prefixSum[i - 1] + arr[i]; } console.log(prefixSum);
Attempts:
2 left
💡 Hint
Remember each element in prefixSum is the sum of all elements up to that index in arr.
✗ Incorrect
The prefix sum array stores cumulative sums. Starting with 2, then 2+4=6, then 6+6=12, then 12+8=20.
❓ Predict Output
intermediateWhat is the value of prefixSum[3] after running this code?
Given the code below, what is the value stored at prefixSum[3]?
DSA Javascript
const arr = [1, 3, 5, 7, 9]; const prefixSum = [0]; for (let i = 0; i < arr.length; i++) { prefixSum[i + 1] = prefixSum[i] + arr[i]; } console.log(prefixSum[3]);
Attempts:
2 left
💡 Hint
prefixSum[3] is sum of arr[0] + arr[1] + arr[2]
✗ Incorrect
prefixSum[3] = arr[0] + arr[1] + arr[2] = 1 + 3 + 5 = 9, but since prefixSum starts with 0 at index 0, prefixSum[3] is sum of first 3 elements, which is 9.
🔧 Debug
advancedWhy does this prefix sum code produce incorrect results?
Look at this code snippet. It tries to build a prefix sum array but the output is wrong. What is the bug?
DSA Javascript
const arr = [1, 2, 3, 4]; const prefixSum = []; for (let i = 0; i < arr.length; i++) { prefixSum[i] = prefixSum[i - 1] + arr[i]; } console.log(prefixSum);
Attempts:
2 left
💡 Hint
Check what happens when i = 0 and prefixSum[i - 1] is accessed.
✗ Incorrect
At i=0, prefixSum[-1] is undefined, so adding arr[0] results in NaN. This breaks the prefix sum calculation.
🚀 Application
advancedHow to find sum of elements between indices 2 and 5 using prefix sum array?
Given a prefix sum array prefixSum where prefixSum[i] is sum of elements from index 0 to i-1 in original array, how do you find sum of elements from index 2 to 5 (inclusive)?
Attempts:
2 left
💡 Hint
Sum from i to j = prefixSum[j+1] - prefixSum[i]
✗ Incorrect
prefixSum array is 1-indexed for sums, so sum from 2 to 5 is prefixSum[6] - prefixSum[2].
🧠 Conceptual
expertWhat is the time complexity to build and query prefix sum array for range sums?
If you have an array of size n, what is the time complexity to build a prefix sum array and then answer m queries asking for sum of elements between two indices?
Attempts:
2 left
💡 Hint
Think about how prefix sums are computed and how queries use them.
✗ Incorrect
Building prefix sum array requires one pass O(n). Each query uses two prefix sums to get range sum in O(1).
