Skip to main content

22. Subarray Sum Equals K

mediumAsked at Indeed

Count 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

Input
nums = [1,1,1], k = 2
Output
2

Example 2

Input
nums = [1,2,3], k = 3
Output
2

Approaches

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.

Output

Press Run or Cmd+Enter to execute

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 →