Challenge - 5 Problems
Prefix Sum Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Prefix Sum Array Construction
What is the output of the following C++ code that constructs a prefix sum array from the given input array?
DSA C++
std::vector<int> arr = {3, 1, 4, 1, 5}; std::vector<int> prefixSum(arr.size()); prefixSum[0] = arr[0]; for (int i = 1; i < arr.size(); i++) { prefixSum[i] = prefixSum[i - 1] + arr[i]; } for (int val : prefixSum) { std::cout << val << " "; }
Attempts:
2 left
💡 Hint
Remember that each prefix sum element is the sum of all elements up to that index.
✗ Incorrect
The prefix sum array is built by adding the current element to the sum of all previous elements. So prefixSum[0] = 3, prefixSum[1] = 3+1=4, prefixSum[2] = 4+4=8, prefixSum[3] = 8+1=9, prefixSum[4] = 9+5=14.
❓ Predict Output
intermediatePrefix Sum Query Result
Given the prefix sum array prefixSum = {2, 5, 9, 14, 20}, what is the sum of elements from index 1 to 3 (inclusive) in the original array?
Attempts:
2 left
💡 Hint
Use prefixSum[j] - prefixSum[i-1] to find sum from i to j.
✗ Incorrect
Sum from index 1 to 3 = prefixSum[3] - prefixSum[0] = 14 - 2 = 12.
🔧 Debug
advancedIdentify the Bug in Prefix Sum Calculation
What error does the following C++ code produce when trying to compute a prefix sum array?
DSA C++
std::vector<int> arr = {1, 2, 3, 4}; std::vector<int> prefixSum(arr.size()); for (int i = 1; i <= arr.size(); i++) { prefixSum[i] = prefixSum[i - 1] + arr[i]; }
Attempts:
2 left
💡 Hint
Check the loop boundary and indexing carefully.
✗ Incorrect
The loop runs with i <= arr.size(), which tries to access prefixSum[arr.size()] and arr[arr.size()], both out of bounds causing runtime error.
🧠 Conceptual
advancedTime Complexity of Prefix Sum Queries
If you have an array of size n and you precompute its prefix sum array, what is the time complexity to answer a sum query for any subarray [i, j]?
Attempts:
2 left
💡 Hint
Think about how prefix sums allow direct calculation without looping.
✗ Incorrect
Once prefix sums are computed, sum queries can be answered in constant time by subtracting prefixSum[i-1] from prefixSum[j].
🚀 Application
expertUsing Prefix Sum to Count Subarrays with Sum K
Given an integer array and an integer K, which approach correctly uses prefix sums to count the number of continuous subarrays whose sum equals K?
Attempts:
2 left
💡 Hint
Think about how to find subarrays efficiently without checking all pairs.
✗ Incorrect
Option D uses a hash map to store counts of prefix sums seen so far, allowing O(n) time counting of subarrays summing to K.
