30. Subarrays with Sum K
β GFG solution to the Subarrays with Sum K problem: count number of subarrays with exact sum K using prefix sum and hash map technique. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given an unsorted array arr[] of integers and a target sum k. Your task is to find the number of subarrays whose sum is exactly equal to the given number k.
A subarray is a contiguous sequence of elements within an array. The goal is to count all possible subarrays where the sum of elements equals the target value k.
π Examples
Example 1
Input: arr[] = [10, 2, -2, -20, 10], k = -10
Output: 3
Explanation: Subarrays: arr[0...3], arr[1...4], arr[3...4] have sum exactly equal to -10.
- arr[0...3] = [10, 2, -2, -20] β sum = -10
- arr[1...4] = [2, -2, -20, 10] β sum = -10
- arr[3...4] = [-20, 10] β sum = -10Example 2
Input: arr[] = [9, 4, 20, 3, 10, 5], k = 33
Output: 2
Explanation: Subarrays: arr[0...2], arr[2...4] have sum exactly equal to 33.
- arr[0...2] = [9, 4, 20] β sum = 33
- arr[2...4] = [20, 3, 10] β sum = 33Example 3
π Constraints
$1 \le \text{arr.size()} \le 10^5$
$-10^3 \le \text{arr}[i] \le 10^3$
$-10^5 \le k \le 10^5$
β
My Approach
The optimal approach uses Prefix Sum technique with a Hash Map to efficiently count subarrays with the target sum:
Prefix Sum + Hash Map
Core Insight:
If prefix sum at index
jissumand prefix sum at indexi-1issum-k, then subarray fromitojhas sumk.We need to count how many times
(current_prefix_sum - k)has occurred before.
Algorithm Steps:
Initialize hash map with
{0: 1}to handle subarrays starting from index 0.Traverse array and maintain running prefix sum.
For each element, check if
(prefix_sum - k)exists in hash map.Add the frequency of
(prefix_sum - k)to result count.Update hash map with current prefix sum.
Key Formula:
subarray_sum[i...j] = prefix_sum[j] - prefix_sum[i-1]If
subarray_sum[i...j] = k, thenprefix_sum[i-1] = prefix_sum[j] - k
Why This Works:
Hash map stores frequency of each prefix sum encountered.
When we find
prefix_sum - kin map, it means there are that many subarrays ending at current position with sumk.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the size of the array. We traverse the array once, and hash map operations (insert/lookup) take O(1) average time.
Expected Auxiliary Space Complexity: O(n), where n is the size of the array. In the worst case, all prefix sums are distinct, requiring O(n) space for the hash map.
π§βπ» Code (C++)
β Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated