"Subarray Sum Equals K" is a medium-difficulty problem that asks you to find the total number of continuous subarrays whose sum equals a target value k. Unlike the "product" version, this problem often involves negative numbers, which makes a simple sliding window approach impossible (since adding an element doesn't necessarily increase the sum). You are given an array of integers and must find the count of all matching subarrays.
This is one of the most frequently asked questions at companies like Meta, Amazon, and Google. It is a brilliant test of whether a candidate can use a Hash Map to store "prefix sums." It evaluates the ability to transform a subarray problem into a "sum of prefixes" problem, which is a key leap in algorithmic thinking. It separates those who rely on brute force from those who understand time-space trade-offs.
The primary pattern for this coding problem is the Prefix Sum combined with a Hash Table. As you iterate through the array, you keep track of the cumulative sum (current_sum). If current_sum - k has been seen before as a prefix sum, it means there is a subarray that sums to k. You store the frequency of each prefix sum in a hash map to quickly look up how many times a particular sum has occurred.
Array: [1, 2, 3], k = 3.
The most common mistake is forgetting to initialize the hash map with {0: 1}. This leads to missing subarrays that sum to k starting from the very beginning of the array. Another mistake is trying to use two pointers/sliding window when the array contains negative numbers. This fails because the window doesn't behave monotonically. Candidates also sometimes forget to store the frequency of the sums and instead only store a boolean, which fails when multiple prefix sums are the same.
To master the Subarray Sum Equals K interview question, practice problems involving "Prefix Sums." Understand the core logic: Sum(i, j) = PrefixSum(j) - PrefixSum(i-1). This formula is the secret to many subarray problems. Be prepared to explain the O(n) time complexity and O(n) space complexity of your solution.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Contiguous Array | Medium | Solve | |
| Subarray Sums Divisible by K | Medium | Solve | |
| Count of Interesting Subarrays | Medium | Solve | |
| Maximum Size Subarray Sum Equals k | Medium | Solve | |
| Make Sum Divisible by P | Medium | Solve |