Subarray Sum Equals K (Array)
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 with input: nums = [1,1,1], k = 2
Example with input: nums = [1,2,3], k = 3
Example with input: nums = [3,4,7,2,-3,1,4,2], k = 7
Algorithm Flow
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.
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
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
