6 May 2024 Shift 1 — Count Subarrays with Sum = K
M · mediumP · Verified PYQAmbiguous I/Oarrays
Problem
Given a sequence of integers “nums” and an integer K, find the total count of contiguous subarrays whose elements sum equals exactly K. Input: comma-separated integers followed by comma then K value.
Constraints
1 <= len(nums) <= 2\*10\*\*4, -1000 <= nums[i] <= 1000
Example
Input
1 2 3 4 5 -4 -3 ,10
Output
2
Use prefix sum + hashmap. For each index, check count of (prefix_sum - K) in map. O(N) time.
Subarrays summing to 10: [1,2,3,4] and [3,4,5,-4,-3+10... check carefully with prefix sum]