Use prefix sums and hashing
Use prefix sums and hashing
A prefix sum array stores the sum of elements before each index. With p[0]=0, the sum of a half-open interval [l,r) equals p[r]-p[l]. A map can store previously seen values or their frequencies for efficient lookup instead of rescanning the input.
package main
import ( "fmt")
func prefix(a []int) []int { p := make([]int, len(a)+1) for i, v := range a { p[i+1] = p[i] + v } return p}func main() { p := prefix([]int{4, -2, 5, 3}) fmt.Println(p) fmt.Println(p[3]-p[1], p[2]-p[2])}Build once in O(n) time and space. Each valid range query costs O(1), with 0<=l<=r<=n. Empty intervals sum to zero. This uses int sums that must fit; modifying the source invalidates the stored prefix sums until rebuilt.
Expected output:
[0 4 2 7 10]3 0Count subarrays with a target sum
package main
import ( "fmt")
func count(a []int, t int) int { seen := map[int]int{0: 1} p, total := 0, 0 for _, v := range a { p += v total += seen[p-t] seen[p]++ } return total}func main() { fmt.Println(count([]int{1, -1, 1}, 1)) fmt.Println(count([]int{0, 0}, 0))}For each ending prefix p, an earlier prefix p-t gives a matching subarray. Count its frequency before adding the current prefix to avoid empty ranges. The initial zero represents the prefix before the first element. With typical constant-time map operations this takes expected O(n) time and O(n) space; Go does not specify map complexity. Counts and arithmetic must fit int.
Expected output:
33Try it locally
Build prefix sums for [2,3,5], then print sums of [0,2) and [1,3).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Algorithms 06: Use prefix sums and hashing
Check the lesson objective before moving on.
Which expression sums [l,r)?
Why initialize seen with 0:1?