MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / kSumSubarrays

Function kSumSubarrays

kotlin/Prefix Sums/KSumSubarrays.kt:1–19  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1fun 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}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected