Bird
0
0
DSA Cprogramming~3 mins

Why Subarray Sum Equals K Using Hash Map in DSA C?

Choose your learning style9 modes available
The Big Idea

What if you could find exact sum periods instantly without checking every possibility?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
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;
}
After
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;
}
What It Enables

This method lets you find all continuous periods summing to k in just one pass through the list, saving time and effort.

Real Life Example

Finding periods of exact sales targets met in daily sales data to analyze performance trends quickly.

Key Takeaways

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.