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. π
π§© Problem Description
π 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
β
My Approach
Prefix Sum + Hash Map
π Time and Auxiliary Space Complexity
π§βπ» Code (C++)
β Code (Java)
π Code (Python)
π§ Contribution and Support
πVisitor Count
Last updated