File tree Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments