Skip to content

Commit 600f156

Browse files
authored
Merge pull request ByteByteGoHq#16 from marttp/kotlin-prefix-sums
Kotlin Chapter 10: Prefix Sums
2 parents ee01580 + 5595b8d commit 600f156

File tree

4 files changed

+73
-0
lines changed

4 files changed

+73
-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+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
fun productArrayWithoutCurrentElement(nums: List<Int>): List<Int> {
2+
val n = nums.size
3+
val res = MutableList(n) { 1 }
4+
// Populate the output with the running left product.
5+
for (i in 1 until n) {
6+
res[i] = res[i - 1] * nums[i - 1]
7+
}
8+
// Multiply the output with the running right product, from right to
9+
// left.
10+
var rightProduct = 1
11+
for (i in n - 1 downTo 0) {
12+
res[i] *= rightProduct
13+
rightProduct *= nums[i]
14+
}
15+
return res
16+
}

kotlin/Prefix Sums/SumBetweenRange.kt

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class SumBetweenRange(nums: IntArray) {
2+
3+
private val prefixSum: IntArray = IntArray(nums.size)
4+
5+
init {
6+
prefixSum[0] = nums[0]
7+
for (i in 1 until nums.size) {
8+
prefixSum[i] = prefixSum[i - 1] + nums[i]
9+
}
10+
}
11+
12+
fun sumRange(i: Int, j: Int): Int {
13+
if (i == 0) {
14+
prefixSum[j]
15+
}
16+
return prefixSum[j] - prefixSum[i - 1]
17+
}
18+
}

0 commit comments

Comments
 (0)