2Brute2Best
🔥0
02

Exact sum + hash map (Prefix Sum Sub-pattern)

Find (or count) contiguous ranges whose sum is exactly K. Walk left to right; at each index look up prefix − K in a map of earlier totals.

Signals in the problem statement
  • ›

    "subarray sum equals K"

  • ›

    "number of subarrays with sum…"

  • ›

    negative numbers or zeros allowed

  • ›

    "zero-sum subarray"

What makes it different

Exact target + negatives is the signal that a sliding window won't work. Zero-sum is the special case K = 0: you're just looking for a total you've seen before.

Questions

ordered from “learn the idea” to “recognise it without help”
  1. 1
    Subarray with 0 Sum
    Basic Anchor·GeeksforGeeks
    Easy
  2. 2
    Count Subarrays with Zero Sum
    Basic Reinforcement·GeeksforGeeks
    Medium
  3. 3
    Subarray Sum Equals K
    Slight Variation·LeetCode #560
    Medium
  4. 4
    Binary Subarrays With Sum
    Basic Anchor·LeetCode #930
    Medium
  5. 5
    Path Sum III (prefix sum on a tree)
    Pattern Transfer·LeetCode #437
    Medium

Template

count-template.cpp
// Count subarrays whose sum is exactly k. Works with negatives and zeros.
long long countSubarrays(vector<int>& nums, int k) {
    unordered_map<long long, int> seen;  // prefix total -> how many times it appeared
    seen[0] = 1;                         // the empty prefix, for ranges starting at index 0
    long long prefix = 0, count = 0;
    for (int x : nums) {
        prefix += x;
        auto it = seen.find(prefix - k); // an earlier total that leaves exactly k between us
        if (it != seen.end()) count += it->second;
        seen[prefix]++;                  // insert AFTER the lookup
    }
    return count;
}
Remember this · Prefix Sum
Trigger
Range sums, "subarray sum equals K" (especially with negatives), equal counts, divisible by K.
Think
If I knew the total up to every index, would the answer become a difference of two totals?
Key question
Which earlier prefix value am I looking for when I stand at index i?