I knew the prefix sum trick going in, which saved me.
Use a hash map to store the frequency of prefix sums seen so far, then for each element compute the current prefix sum and check if (current prefix sum - T) exists in the map, adding its frequency to the count. This yields O(n) time and handles negative numbers naturally because prefix sums can decrease. Explain that the empty prefix (sum 0) is initialized with frequency 1 to account for subarrays starting at index 0.
Pro tip: Mention that this is a classic application of the 'two-sum' pattern to subarrays, and that the same technique works for counting subarrays with sum divisible by K or with XOR equal to a target. Also, clarify that the hash map stores frequencies, not just presence, to count all valid subarrays.
Restate the problem: count contiguous subarrays summing to T in O(n) time. Confirm that the array can contain negative numbers and that T can be zero. Ask if the array is mutable or if extra space is allowed (hash map uses O(n) space).
Describe how to compute prefix sums on the fly and use a hash map to store the frequency of each prefix sum seen so far. For each index, check if (current prefix sum - T) is in the map; if so, add its frequency to the count. Then add the current prefix sum to the map.
Initialize the map with {0: 1} to account for the empty prefix (subarrays starting at index 0). Explain that negative numbers are handled because prefix sums can decrease, but the hash map still correctly identifies previous sums. For T=0, the approach counts subarrays with sum zero, including empty subarrays? No, empty subarrays are not counted because we only consider contiguous subarrays of length >=1; the empty prefix is only used as a starting point.
Choose a small array (e.g., [1, -1, 1, -1] with T=0) and step through the algorithm to demonstrate correctness, especially with negative numbers and T=0. Show how the count updates and how the map frequencies change.
State that time complexity is O(n) and space complexity is O(n) due to the hash map. Mention that this is optimal for time, but if space is a concern, a two-pointer approach could be used for non-negative numbers, but it fails with negatives. Emphasize that the hash map approach is necessary for general integers.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.