Skip to main content
TRACK B · ALGORITHMmedium•NOVEMBER 2026•6 MIN

Hash Map + Prefix Sum: Subarrays With Negatives

Turn O(n²) subarray sum searches—even with negative numbers—into one O(n) pass.

prefix sumhash maparrayssubarraysnegatives

The core idea

Any contiguous subarray sum nums[l+1..r] equals prefix[r] - prefix[l]. Setting that equal to K means you just look up how many earlier prefixes equaled prefix[r] - K.

Watch it run

Step through the trace below (or turn on Predict Mode) to watch the invariant hold at every step.

LOADING HASH MAP + PREFIX SUM SIM...

What to say out loud

Canonical Python template

def subarray_sum(nums: list[int], k: int) -> int:
    counts = {0: 1}
    prefix = ans = 0
    for x in nums:
        prefix += x
        ans += counts.get(prefix - k, 0)
        counts[prefix] = counts.get(prefix, 0) + 1
    return ans

Related Lab Entries