Skip to content

Commit 5595b8d

Browse files
committed
Add K Sum Subarrays
1 parent aecb6d2 commit 5595b8d

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

kotlin/Prefix Sums/KSumSubarrays.kt

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
fun kSumSubarrays(nums: List<Int>, k: Int): Int {
2+
val n = nums.size
3+
var count = 0
4+
// Populate the prefix sum array, setting its first element to 0.
5+
val prefixSum = IntArray(n + 1)
6+
for (i in 0 until n) {
7+
prefixSum[i + 1] = prefixSum[i] + nums[i]
8+
}
9+
// Loop through all valid pairs of prefix sum values to find all
10+
// subarrays that sum to 'k'.
11+
for (j in 1..n) {
12+
for (i in 1..j) {
13+
if (prefixSum[j] - prefixSum[i - 1] == k) {
14+
count++
15+
}
16+
}
17+
}
18+
return count
19+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
fun kSumSubarraysOptimized(nums: IntArray, k: Int): Int {
2+
var count = 0
3+
// Initialize the map with 0 to handle subarrays that sum to 'k'
4+
// from the start of the array.
5+
val prefixSumMap = mutableMapOf(0 to 1)
6+
var currPrefixSum = 0
7+
for (num in nums) {
8+
// Update the running prefix sum by adding the current number.
9+
currPrefixSum += num
10+
// If a subarray with sum 'k' exists, increment 'count' by the
11+
// number of times it has been found.
12+
if (currPrefixSum - k in prefixSumMap) {
13+
count += prefixSumMap[currPrefixSum - k]!!
14+
}
15+
// Update the frequency of 'currPrefixSum' in the hash map.
16+
val freq = prefixSumMap.getOrDefault(currPrefixSum, 0)
17+
prefixSumMap[currPrefixSum] = freq + 1
18+
}
19+
return count
20+
}

0 commit comments

Comments
 (0)