Count subarrays equal to target
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates array manipulation, cumulative-sum reasoning, and algorithmic complexity analysis for counting contiguous subarrays that equal a target value.
Constraints
- 1 <= nums.length <= 2 * 10^4 (an empty array yields 0)
- -1000 <= nums[i] <= 1000
- -10^7 <= k <= 10^7
- Prefix sums can reach magnitudes around 2 * 10^7, well within 32-bit range, but use a 64-bit accumulator if element bounds are widened
Examples
Input: ([1, 1, 1], 2)
Expected Output: 2
Explanation: The subarrays [1,1] at indices 0-1 and at indices 1-2 each sum to 2.
Input: ([1, 2, 3], 3)
Expected Output: 2
Explanation: [1,2] sums to 3 and the single element [3] sums to 3.
Input: ([1, -1, 0], 0)
Expected Output: 3
Explanation: [1,-1], [1,-1,0], and the lone [0] all sum to 0 — negatives and zeros are handled by the prefix-sum map.
Input: ([], 0)
Expected Output: 0
Explanation: Empty array has no subarrays, so the answer is 0.
Input: ([5], 5)
Expected Output: 1
Explanation: Single-element array where that element equals k.
Input: ([3, 4, 7, 2, -3, 1, 4, 2], 7)
Expected Output: 4
Explanation: [3,4], [7], [7,2,-3,1], and [1,4,2] each sum to 7, demonstrating overlapping matches with negatives.
Input: ([-1, -1, 1], 0)
Expected Output: 1
Explanation: Only [-1,1] (indices 1-2) sums to 0; all-negative prefixes are still tracked correctly.
Input: ([0, 0, 0], 0)
Expected Output: 6
Explanation: Every contiguous slice sums to 0: three single zeros, two length-2 slices, and one length-3 slice = 6. Repeated zero prefix sums in the map drive the count up.
Hints
- A sliding window does not work here because negative numbers and zeros make the running sum non-monotonic — shrinking the window can both decrease and increase the sum.
- Define prefix[i] = nums[0] + ... + nums[i-1]. A subarray (i, j] sums to k exactly when prefix[j] - prefix[i] = k, i.e. prefix[i] = prefix[j] - k.
- Scan left to right keeping a running prefix sum and a hash map from prefix-sum value to how many times it has occurred. For each position add map[running_sum - k] to the answer, then record the current running_sum.
- Seed the map with {0: 1} before the loop so that subarrays starting at index 0 (where prefix[i] = 0) are counted.