~/problems / Arrays & hashing / Prefix sums and difference arrays

Count subarrays with a target sum (any sign)

medium ~25 min

Write count_subarrays(nums: list[int], target: int) -> int.

Count the contiguous, non-empty subarrays of nums whose elements add up to exactly target. Values can be negative or zero.

Example: nums = [1, 2, -1, 2, 1], target = 3 gives 3: [1, 2], [2, -1, 2] and [2, 1]. nums = [0, 0, 0], target = 0 gives 6.

Constraints: 1 <= len(nums) <= 2 * 10^5, -10^9 <= nums[i], target <= 10^9. The answer can exceed 32 bits.

Checking every start/end pair is O(n²) and fails the large test. Aim for O(n).

Show hint

negatives rule out a sliding window. Write each subarray sum as the difference of two prefix sums; while scanning, what do you need to remember about the earlier prefix sums to count the matches ending here?

Topic: Prefix sums and difference arrays. O(1) range sums (1D and 2D); O(1) range updates with difference arrays.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc