Count target-sum subarrays
Return how many nonempty contiguous subarrays sum to target. Values may be negative or zero.
prefix, target = 5, 2
earlier_counts = {0: 1, 3: 2}
print(earlier_counts.get(prefix-target, 0))Reason about the state
For each prefix sum, count earlier prefixes equal to current minus target. Seed the zero prefix once and update counts after querying. Before writing code, identify what each variable means after one iteration. Walk through the example and explain why the next transition preserves that meaning. Then check the smallest permitted input and a case with repeated values. A correct answer follows the contract for every input, including the boundary cases in the checks. Keep any input mutation within the stated rules; return a fresh result when the task asks for one.
Your task
Return how many nonempty contiguous subarrays sum to target. Values may be negative or zero.
The explanation opens here once every check passes.