Code Logo

Subarray Sum Equals K (Array)

Published at05 Jan 2026
Array Manipulation Hard 23 views
Like13

This challenge becomes much easier once you know exactly what to keep, change, or count. In Subarray Sum Equals K, you are trying to work toward the right number by following one clear idea.

This one is about building the best total or working out a final amount. You may need to choose which values should be included and which ones should be skipped. Sometimes the biggest number is not the smartest first choice if it hurts the rest of the plan. The goal is to finish with the best overall total, not just one good moment.

For example, if the input is nums = [1,1,1], k = 2, the answer is 2. Example with input: nums = [1,1,1], k = 2 Another example is nums = [1,2,3], k = 3, which gives 2. Example with input: nums = [1,2,3], k = 3This is one of the harder problems, so it is normal if the answer is not obvious right away. The key is thinking about the whole plan, not only one choice at a time.

Example Input & Output

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

Example with input: nums = [1,1,1], k = 2

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

Example with input: nums = [1,2,3], k = 3

Example 3
Input
nums = [3,4,7,2,-3,1,4,2], k = 7
Output
4
Explanation

Example with input: nums = [3,4,7,2,-3,1,4,2], k = 7

Algorithm Flow

Recommendation Algorithm Flow for Subarray Sum Equals K (Array)

Solution Approach

Count subarrays whose sum equals k. Use a hash map storing running sum frequencies. Maintain a running sum as you iterate. For each position, check if runningSum - k exists in the map. If so, add its count to the total. Update the map with the current running sum.

function subarraySum(nums, k) {
  var map = {0: 1}, sum = 0, count = 0;
  for (var i = 0; i < nums.length; i++) {
    sum += nums[i];
    if (map[sum - k]) count += map[sum - k];
    map[sum] = (map[sum] || 0) + 1;
  }
  return count;
}

The map tracks how many times each prefix sum has occurred. When sum - k exists in the map, those prefix positions mark the start of a valid subarray ending at the current index.

Time complexity is O(n), space complexity is O(n).

Best Answers

java
import java.util.*;
class Solution {
    public int subarray_sum(Object nums, Object k) {
        int[] n_arr = (int[]) nums;
        int target = (int) k;
        int count = 0, current = 0;
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, 1);
        for (int x : n_arr) {
            current += x;
            if (map.containsKey(current - target)) count += map.get(current - target);
            map.put(current, map.getOrDefault(current, 0) + 1);
        }
        return count;
    }
}