22. Subarray Sum Equals K
mediumAsked at IndeedCount contiguous subarrays whose sum equals k — the prefix-sum hash map approach models Indeed's click-window aggregation in A/B test signal computation.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.
Constraints
1 <= nums.length <= 2 * 10^4-1000 <= nums[i] <= 1000-10^7 <= k <= 10^7
Examples
Example 1
nums = [1,1,1], k = 22Example 2
nums = [1,2,3], k = 32Approaches
1. Brute force
Check all O(n^2) subarrays by iterating over every pair of start and end indices.
- Time
- O(n^2)
- Space
- O(1)
function subarraySum(nums, k) {
let count = 0;
for (let i = 0; i < nums.length; i++) {
let sum = 0;
for (let j = i; j < nums.length; j++) {
sum += nums[j];
if (sum === k) count++;
}
}
return count;
}Tradeoff:
2. Prefix sum + hash map
Track running prefix sums in a hash map; for each index check how many prior prefixes equal (currentSum - k), finding matching subarrays in O(1) per step.
- Time
- O(n)
- Space
- O(n)
function subarraySum(nums, k) {
const prefixCount = new Map([[0, 1]]);
let sum = 0, count = 0;
for (const n of nums) {
sum += n;
count += (prefixCount.get(sum - k) || 0);
prefixCount.set(sum, (prefixCount.get(sum) || 0) + 1);
}
return count;
}Tradeoff:
Indeed-specific tips
Indeed loves prefix-sum problems; explain that initializing the map with {0:1} handles the case where the entire prefix equals k — this detail distinguishes strong candidates.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Subarray Sum Equals K and other Indeed interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →