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

Function tripletSum

kotlin/Two Pointers/TripletSum.kt:1–22  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1fun tripletSum(nums: List<Int>): List<List<Int>> {
2 val triplets = mutableListOf<List<Int>>()
3 val sortedNums = nums.sorted()
4 for (i in sortedNums.indices) {
5 // Optimization: triplets consisting of only positive numbers
6 // will never sum to 0.
7 if (sortedNums[i] > 0) {
8 break
9 }
10 // To avoid duplicate triplets, skip 'a' if it's the same as
11 // the previous number.
12 if (i > 0 && sortedNums[i] == sortedNums[i - 1]) {
13 continue
14 }
15 // Find all pairs that sum to a target of '-a' (-nums[i]).
16 var listOfPair = pairSumSortedAllPairs(sortedNums, i + 1, -1 * sortedNums[i])
17 for (l in listOfPair) {
18 triplets.add(listOf(sortedNums[i], l[0], l[1]))
19 }
20 }
21 return triplets
22}
23
24fun pairSumSortedAllPairs(nums: List<Int>, start: Int, target: Int): List<List<Int>> {
25 val listOfPair = mutableListOf<List<Int>>()

Callers

nothing calls this directly

Calls 2

pairSumSortedAllPairsFunction · 0.70
addMethod · 0.45

Tested by

no test coverage detected