759. Payments reconciliation: count ledger runs that net to an exact amount
You work on payments reconciliation. The ledger for one merchant is a list of transaction amounts in order: sales are positive, refunds and chargebacks are negative, and adjustments can be 0. A dispute says "a run of consecutive transactions netted to exactly X". Finance wants to know how many runs could match, and how long the longest one is, so they know how far back to look.
Write count_target_subarrays(nums, target, mode='count').
- nums: a list of ints (negative and zero allowed), possibly empty.
- mode 'count': return how many contiguous, non-empty runs nums[i..j] sum to exactly target.
- mode 'longest': return the length of the longest such run, or 0 if there is none.
Constraints:
- len(nums) can be 100,000, so checking every (i, j) pair (about 5 billion pairs) is too slow. Aim for one pass.
- Because refunds are negative, the running sum can go down, so a sliding window that shrinks when the sum is too big gives wrong answers.
- target can be 0 or negative. Only non-empty runs count, so never count an empty run as summing to 0.
Idea: with prefix sums P, the run i..j sums to target exactly when P[j] - P[i-1] = target. Count earlier prefix sums in a dict, and for 'longest' remember where each prefix sum first appeared.
def count_target_subarrays(nums, target, mode='count')Example 1
Input: count_target_subarrays([1, 1, 1], 2)
Output: 2 (the runs [1, 1] starting at index 0 and at index 1)
Example 2
Input: count_target_subarrays([1, -1, 5, -2, 3], 3, 'longest')
Output: 4 (the run [1, -1, 5, -2])
Example 3
Input: count_target_subarrays([120, -20, -100, 250, -250, 40], 0)
Output: 3, and in mode 'longest' it returns 5
Constraints
- Up to 200,000 values.
- Values and target are integers, possibly negative.
Hint 1
Write down the prefix sums for a small example.
Hint 2
Seed the map with prefix 0.
Hint 3
For 'longest', keep the first index only.
Common mistakes
- Using a sliding window, which breaks when values can be negative.
- Forgetting the empty prefix, which misses windows that start at index 0.
- Updating the map before the lookup, which counts an empty window when target is 0.
Understand the idea
Prefix sums turn a question about windows into a question about pairs of points. Window sum = P[end] - P[start]. Asking for windows with sum k becomes asking for earlier prefixes equal to P[end] - k, which a hash map answers in O(1). With [1, 1, 1] and k = 2 the prefixes are 0, 1, 2, 3, and the pairs (0, 2) and (1, 3) give the two windows. Unlike a two-pointer window, this works with negative numbers.