Counting Subarrays with Sum K in Java

Day 28 Problem Statement: Given an array arr[] of postive and negative integers, the objective is to find the number of subarrays having a sum exactly equal to a given number k. Examples:  Input : arr[] = [10, 2, -2, -20, 10], k = -10 Output : 3 Explanation: Subarrays: arr[0...3], arr[1...4], arr[3...4] have sum equal to -10. Input : arr[] = [9, 4, 20, 3, 10, 5], k = 33 Output : 2 Explanation: Subarrays: arr[0...2], arr[2...4] have sum equal to 33. Input : arr[] = [1, 3, 5], k = 2 Output : 0 Explanation: No subarrays with 0 sum. Approach : To count subarrays with sum k, we use a hash map to store the frequency of prefix sums. At each index, we calculate the current prefix sum currSum and check if (currSum - k) exists in the map. If it does, it means there are subarrays ending at the current index with sum k, and we add their count to the result. Then we update the frequency of currSum in the map. #HappyCoding #DSA #java #hashing

To view or add a comment, sign in

Explore content categories