Subarray Sum Equals K
Quick Overview
Given an array of integers and a target k, find the total number of contiguous subarrays whose sum equals k. Tests prefix sum and hash map patterns frequently seen at Meta.
Meta
0
Given an array of integers and a target k, find the total number of contiguous subarrays whose sum equals k. Tests prefix sum and hash map patterns frequently seen at Meta.
Meta uses this as a medium onsite coding question because the brute-force O(n^2) answer is easy and the interviewer wants to see you reach the prefix-sum plus hash map insight on your own. They also check that you handle negative numbers and zeros, which rule out a sliding window.
What the Interviewer Expects
- Explain why a sliding window fails when the array contains negative numbers
- Derive the prefix-sum identity: a subarray i..j sums to k when prefix[j] - prefix[i-1] = k
- Seed the hash map with {0: 1} and explain why
- Write clean O(n) time, O(n) space code
- Trace a small example such as [1, 1, 1] with k = 2
- Cover edge cases like zeros, negatives and an empty array
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you return the subarrays themselves instead of the count?
- How would you find the longest subarray that sums to k?
- If all numbers are positive, can you get O(1) extra space?
- How would you count subarrays whose sum is divisible by k?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Problem Analysis
To solve the problem of finding the total number of contiguous subarrays whose sum equals k, we can leverage the prefix sum technique combined with a hash map. The prefix sum allows us to compute the ...
Approach
- Initialize a hash map (or dictionary) to store the frequency of prefix sums, starting with {0: 1} to account for any subarrays that sum to k starting from the first element.
- Initialize two varia...