What if you could find exact sum periods instantly without checking every possibility?
Why Subarray Sum Equals K Using Hash Map in DSA C?
Imagine you have a long list of daily expenses, and you want to find if there is a continuous period where the total spending equals exactly $k. Doing this by checking every possible period manually would take forever.
Manually checking every possible continuous period means adding up many sums repeatedly. This is slow and tiring, especially if the list is very long. It's easy to make mistakes and miss some periods.
Using a hash map, we can remember sums we have seen before. This helps us quickly find if a previous sum lets us get the target sum by subtracting. It makes the search fast and simple.
int countSubarrays(int* arr, int size, int k) {
int count = 0;
for (int start = 0; start < size; start++) {
int sum = 0;
for (int end = start; end < size; end++) {
sum += arr[end];
if (sum == k) count++;
}
}
return count;
}int countSubarrays(int* arr, int size, int k) {
int count = 0, sum = 0;
HashMap map = createHashMap();
put(map, 0, 1);
for (int i = 0; i < size; i++) {
sum += arr[i];
count += get(map, sum - k);
put(map, sum, get(map, sum) + 1);
}
return count;
}This method lets you find all continuous periods summing to k in just one pass through the list, saving time and effort.
Finding periods of exact sales targets met in daily sales data to analyze performance trends quickly.
Manual sum checking is slow and error-prone.
Hash map stores sums seen to find matches fast.
Efficiently counts all subarrays summing to k in one pass.
