Skip to main content

Practice · 3 of 3

Prefix Sums & Range Queries

CHALLENGE
Difficulty: intermediate+25 XP

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).

Back to lesson: Practice: Algorithms Lab