Data Structures19 sections · 729 units
Open in Course

Subarray Sum - Why Initialize with 0

Handling edge case

Why start with freq[0]=1freq[0] = 1? Consider array [3][3] with k=3k = 3.

After processing:

  • prefixSum=3prefixSum = 3
  • We look for prefixSumk=0prefixSum - k = 0 in the map
  • If 00 wasn't in the map, we'd miss this valid subarray

The prefix sum 00 represents the empty prefix (sum before index 00). A subarray from index 00 to jj has sum prefix[j]prefix[1]=prefix[j]0=prefix[j]prefix[j] - prefix[-1] = prefix[j] - 0 = prefix[j].