Count subarrays equal to target
Company: Akuna Capital
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This interview question evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer for Count subarrays equal to target states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- 1 <= nums.length <= 2 * 10^4 (an empty array yields 0)
- -1000 <= nums[i] <= 1000 (values may be negative or zero)
- -10^7 <= k <= 10^7
- Subarrays are contiguous and non-empty; count every distinct index range that qualifies.
Examples
Input: ([1, 1, 1], 2)
Expected Output: 2
Explanation: The two overlapping subarrays [1,1] (indices 0-1 and 1-2) each sum to 2.
Input: ([1, 2, 3], 3)
Expected Output: 2
Explanation: [1,2] and the single element [3] both sum to 3.
Input: ([1, -1, 1, -1], 0)
Expected Output: 4
Explanation: [1,-1] (twice), [-1,1], and the whole array [1,-1,1,-1] all sum to 0 — negatives produce repeated prefix sums.
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.
Input: ([], 0)
Expected Output: 0
Explanation: No elements means no non-empty subarrays, so the count is 0.
Input: ([5], 5)
Expected Output: 1
Explanation: The single subarray [5] matches k=5.
Input: ([5], 3)
Expected Output: 0
Explanation: The only subarray [5] sums to 5, not 3.
Input: ([-1, -1, 1], 0)
Expected Output: 1
Explanation: Only [-1,1] (indices 1-2) sums to 0; demonstrates correctness with all-negative prefixes.
Input: ([0, 0, 0], 0)
Expected Output: 6
Explanation: Every one of the 6 contiguous subarrays of three zeros sums to 0, showing duplicate prefix sums are counted fully.
Hints
- A subarray sum equals prefix[j] - prefix[i]. Fix the right end j and ask: how many earlier prefixes i satisfy prefix[j] - prefix[i] = k, i.e. prefix[i] = prefix[j] - k?
- Keep a hash map from prefix-sum value to how many times it has occurred. Before inserting the current prefix, add freq[prefix - k] to your answer.
- Seed the map with {0: 1} so subarrays that start at index 0 are counted. Because you query for prefix - k BEFORE inserting the current prefix, you never count an empty subarray.