Bird
0
0
DSA Cprogramming~30 mins

Subarray Sum Equals K Using Hash Map in DSA C - Build from Scratch

Choose your learning style9 modes available
Subarray Sum Equals K Using Hash Map
📖 Scenario: Imagine you are analyzing daily sales numbers for a small shop. You want to find how many continuous days had sales that add up exactly to a target number k. This helps the shop owner understand patterns in sales.
🎯 Goal: Build a program that counts the number of continuous subarrays in an integer array whose sum equals a given target k. Use a hash map (implemented with arrays) to efficiently track sums.
📋 What You'll Learn
Create an integer array called sales with the exact values: {1, 2, 3, -2, 5}
Create an integer variable called k and set it to 5
Implement a function subarraySum that takes sales, its length, and k, and returns the count of continuous subarrays summing to k using a hash map
Print the result returned by subarraySum
💡 Why This Matters
🌍 Real World
Finding continuous periods where sales or data points sum to a target helps in financial analysis, detecting patterns, and anomaly detection.
💼 Career
This technique is useful in software engineering roles involving data analysis, algorithm optimization, and performance-critical applications.
Progress0 / 4 steps
1
Create the sales data array
Create an integer array called sales with the exact values {1, 2, 3, -2, 5} and an integer variable n set to the length of sales.
DSA C
Hint

Use int sales[] = {1, 2, 3, -2, 5}; and int n = 5; to create the array and its size.

2
Set the target sum k
Create an integer variable called k and set it to 5.
DSA C
Hint

Use int k = 5; to set the target sum.

3
Implement the subarraySum function using a hash map
Implement a function called subarraySum that takes int* nums, int numsSize, and int k as parameters and returns an int. Use a hash map (array) to count how many continuous subarrays sum to k. Use variables count, sum, and a fixed-size hash map array hashMap of size 20001 to store frequencies of prefix sums. Initialize hashMap[10000] to 1 to handle zero sum offset. Iterate over nums, update sum, and update count by checking hashMap[sum - k + 10000]. Update hashMap[sum + 10000] accordingly.
DSA C
Hint

Use a fixed-size array as a hash map with offset 10000 to handle negative sums. Initialize hashMap[10000] to 1 for the empty prefix sum. Loop through nums, update sum, and update count and hashMap accordingly.

4
Print the count of subarrays summing to k
Print the result of calling subarraySum with sales, n, and k.
DSA C
Hint

Use printf("%d\n", subarraySum(sales, n, k)); inside main to print the count.