Count subarrays summing to target
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of prefix-sum concepts, use of linear-time data structures, and competence in handling negative numbers and edge cases such as zero targets and empty prefixes.
Constraints
- 1 <= nums.length <= 2 * 10^4 (an empty array trivially returns 0)
- -1000 <= nums[i] <= 1000
- -10^7 <= target <= 10^7
- The array may contain negatives, zeros, and duplicate values.
Examples
Input: ([1, 1, 1], 2)
Expected Output: 2
Explanation: Subarrays [1,1] at indices 0..1 and [1,1] at indices 1..2 each sum to 2.
Input: ([1, 2, 3], 3)
Expected Output: 2
Explanation: [1,2] and [3] both sum to 3.
Hints
- Define prefix[i] = nums[0] + ... + nums[i-1]. A subarray (l, r) sums to target exactly when prefix[r+1] - prefix[l] == target.
- Rearrange: for each running prefix sum S, you need the count of earlier prefix sums equal to S - target. Maintain a hash map from prefix-sum value to how many times it has occurred so far.
- Seed the map with {0: 1} before the loop. That entry represents the empty prefix and is what lets a subarray starting at index 0 be counted (it handles target sums that begin at the very front, including target = 0).
- Because you only ever look at prefix sums seen *before* the current index, the method works correctly with negative numbers and zeros where sliding windows fail.