Practice ยท 3 of 3
Prefix Sums & Range Queries
Implement:
- static long[] prefixSums(int[] xs) โ length n+1, pre[0]=0,
pre[i+1] = pre[i] + xs[i].
- static long rangeSum(long[] pre, int l, int r) โ sum of [l, r)
via pre[r] - pre[l].
- static int countSubarraysWithSum(int[] xs, int target) โ number of
contiguous subarrays summing exactly to target, using the prefix map
trick (count of earlier prefixes with pre[j] == pre[i] - target).
[-2, 2, -2, 2], target 0 โ 5 subarrays (each zero-sum run counts).
Difficulty: intermediate
Press Submit to check your solution.
Back to lesson: Practice: Algorithms Lab