📖 Scenario: You are analyzing daily sales data for a small store. You want to find how many periods (continuous days) had total sales exactly equal to a target number.
🎯 Goal: Build a program that counts the number of continuous subarrays in a list of daily sales that sum up to a given target k using a hash map for efficient lookup.
📋 What You'll Learn
Create an integer array called sales with the exact values: 1, 2, 3, 4, 2
Create an integer variable called k and set it to 5
Use a Dictionary<int, int> called prefixSums to store cumulative sums and their counts
Use a for loop with variable i to iterate over sales
Calculate cumulative sums and update prefixSums to count subarrays summing to k
Print the final count of subarrays that sum to k
💡 Why This Matters
🌍 Real World
Finding periods of exact sales targets helps businesses analyze performance and plan promotions.
💼 Career
This technique is useful in data analysis, software development, and coding interviews where efficient subarray sum problems are common.
Progress0 / 4 steps
1
Create the sales data array
Create an integer array called sales with these exact values: 1, 2, 3, 4, 2
DSA C#
Hint
Use int[] sales = {1, 2, 3, 4, 2}; to create the array.
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
Count subarrays summing to k using a hash map
Create a Dictionary<int, int> called prefixSums and initialize it with 0 key and value 1. Then create integer variables count and currentSum set to 0. Use a for loop with variable i to iterate over sales. Inside the loop, add sales[i] to currentSum. Check if prefixSums contains key currentSum - k and if yes, add its value to count. Then update prefixSums by adding or incrementing the count for currentSum.
DSA C#
Hint
Use a dictionary to store counts of prefix sums. Update count when currentSum - k is found.
4
Print the count of subarrays summing to k
Print the value of the variable count using Console.WriteLine(count);
DSA C#
Hint
Use Console.WriteLine(count); to print the final count.
Practice
(1/5)
1. What is the main purpose of using a hash map in the Subarray Sum Equals K problem?
easy
A. To store cumulative sums and their frequencies for quick lookup
B. To sort the array elements before processing
C. To store the original array elements as keys
D. To reverse the array for easier traversal
Solution
Step 1: Understand the problem goal
The problem wants to find subarrays whose sums equal a target value k.
Step 2: Role of hash map in solution
The hash map stores cumulative sums seen so far and how many times they occurred, enabling quick checks for needed sums.
Final Answer:
To store cumulative sums and their frequencies for quick lookup -> Option A
Quick Check:
Hash map stores sums = A [OK]
Hint: Hash map tracks sums to find subarrays fast [OK]
Common Mistakes:
Thinking hash map stores array elements directly
Assuming sorting is needed
Using hash map to reverse array
2. Which of the following is the correct way to declare a hash map (Dictionary) in C# to store cumulative sums and their counts?
easy
A. Dictionary sumCounts = new Dictionary();
B. HashMap sumCounts = new HashMap();
C. Map sumCounts = new Map();
D. Dictionary sumCounts = new Dictionary();
Solution
Step 1: Identify correct C# dictionary syntax
C# uses Dictionary<TKey, TValue> with new Dictionary<TKey, TValue>() to declare hash maps.
Step 2: Check each option
Dictionary sumCounts = new Dictionary(); uses correct generic syntax. Options B and C use Java-like syntax. Dictionary sumCounts = new Dictionary(); misses generic types.
Final Answer:
Dictionary sumCounts = new Dictionary(); -> Option A
Quick Check:
C# Dictionary syntax = A [OK]
Hint: Use Dictionary in C# for hash maps [OK]
Common Mistakes:
Using Java HashMap syntax in C#
Omitting generic type parameters
Using non-existent Map type in C#
3. What is the output of the following C# code snippet?
int[] nums = {1, 2, 3};
int k = 3;
int count = 0;
Dictionary sumCounts = new Dictionary();
sumCounts[0] = 1;
int sum = 0;
foreach (int num in nums) {
sum += num;
if (sumCounts.ContainsKey(sum - k)) {
count += sumCounts[sum - k];
}
if (sumCounts.ContainsKey(sum)) {
sumCounts[sum]++;
} else {
sumCounts[sum] = 1;
}
}
Console.WriteLine(count);
medium
A. 1
B. 0
C. 3
D. 2
Solution
Step 1: Calculate cumulative sums and check counts
nums = [1,2,3], k=3. sumCounts starts with {0:1}.
- sum=1: sum-k= -2 (not in sumCounts), count=0, sumCounts={0:1,1:1}
- sum=3: sum-k=0 (in sumCounts=1), count=1, sumCounts={0:1,1:1,3:1}
- sum=6: sum-k=3 (in sumCounts=1), count=2, sumCounts={0:1,1:1,3:1,6:1}
Step 2: Final count of subarrays with sum k
Count is 2 because subarrays [1,2] and [3] sum to 3.
Final Answer:
2 -> Option D
Quick Check:
Subarrays count = 2 [OK]
Hint: Track cumulative sums and check sum-k in map [OK]
Common Mistakes:
Not initializing sumCounts with {0:1}
Forgetting to update count correctly
Misunderstanding sum-k lookup
4. Identify the bug in this C# code snippet for counting subarrays summing to k:
int[] nums = {1, 1, 1};
int k = 2;
int count = 0;
Dictionary sumCounts = new Dictionary();
int sum = 0;
foreach (int num in nums) {
sum += num;
if (sumCounts.ContainsKey(sum - k)) {
count += sumCounts[sum - k];
}
sumCounts[sum] = 1;
}
Console.WriteLine(count);
medium
A. nums array is empty
B. sumCounts is not initialized with sum 0 count 1
C. count is not incremented correctly
D. sum variable is not updated inside the loop
Solution
Step 1: Check initialization of sumCounts
sumCounts should start with {0:1} to count subarrays starting at index 0, but here it is empty.
Step 2: Check updating sumCounts inside loop
sumCounts[sum] = 1 overwrites counts instead of incrementing, but main bug is missing initial {0:1}.
Final Answer:
sumCounts is not initialized with sum 0 count 1 -> Option B
Quick Check:
Initialize sumCounts[0] = 1 [OK]
Hint: Always initialize sumCounts with {0:1} before loop [OK]
Common Mistakes:
Not initializing sumCounts with {0:1}
Overwriting counts instead of incrementing
Ignoring sum-k lookup logic
5. Given the array nums = {3, 4, 7, 2, -3, 1, 4, 2} and k = 7, how many subarrays sum to k using the hash map approach?
hard
A. 5
B. 3
C. 4
D. 6
Solution
Step 1: Calculate cumulative sums and track counts