[Question]: In an array nums
and an integer k
, return the total number of subarrays whose sum equals to k
.
Example 1:
Input: nums = [1,1,1], k = 2 Output: 2
Example 2:
Input: nums = [1,2,3], k = 3 Output: 2
// TC: O(n)
// SC: O(n)
func subarraySumK(_ arr: [Int], _ k: Int) ->Int {
var result = 0, sum = 0
var dict: [Int:Int] = [:]
dict[0] = 1
for num in arr {
sum += num
if let val = dict[sum - k] {
result += val
}
dict[sum, default: 0] += 1// Storing the previous sum value which can be added to result.
}
return result
}
let subArr = [1,0,2,3]
let kSum = 3
let opKsum = subarraySumK(subArr, kSum)
print(" subArr with k sum is-->", opKsum)// 2 (1,2 & 3)