awelgorithms

Subarray sum equals k via a prefix map

Updated

Need a[L..R]=k iff p[R+1]−p[L]=k iff p[L]=p[R+1]−k. Store seen prefixes in a map. At each new p, look up p−k. A hit is a subarray ending here.

What to focus on

Leading-zero: start seen {0:1} (or 0→index −1). Update the map after the lookup so the empty-left case still works and you do not use the current p as L.

Worked examples

hit [1,9]

a = [4, 1, 9, 1], k = 10, p runs 0,4,5,14,15
  1. seen starts {0}
  2. at p=14 need 4, map has 4 after i=0
  3. L=1 R=2

Result: [1, 9]

hit [9,1]

a = [1, 4, 9, 1], k = 10, p runs 0,1,5,14,15
  1. at p=15 need 5
  2. 5 was stored after i=1
  3. L=2 R=3

Result: [9, 1]

two hits

a = [4, 1, 9, 1], k = 10, count with seen counts
  1. p=14 hits 4 → +1
  2. p=15 hits 5 → +1

Result: count 2

Try it

Write subarraySumK(a, k). a is the input array. k is the target sum. Leading-zero p[i] covers a[0..i). Return each hit slice. Look up p−k, then insert p. [4, 1, 9, 1] k=10 → [1, 9] then [9, 1] [1, 4, 9, 1] k=10 → [9, 1] [4, 1, 9, 1] k=10 count → 2

a is a non-empty array of integers. k is an integer. A contiguous slice summing to k exists in each find-one example.