Skip to content

Instantly share code, notes, and snippets.

@Husseinhj
Last active August 8, 2022 10:31
Show Gist options
  • Save Husseinhj/de1dfff478752f87313bcc11e295fa17 to your computer and use it in GitHub Desktop.
Save Husseinhj/de1dfff478752f87313bcc11e295fa17 to your computer and use it in GitHub Desktop.
Two Combination Sum
package org.kotlinlang.play
//Playground: https://pl.kotl.in/5Cjs0Zde6
fun main() {
val k = 10
val sample = arrayOf(1,1,2,23,4,9,13,6,9)
val result = indexOfAddUp(sample, k)
println(result)
}
fun indexOfAddUp(sample: Array<Int>, k: Int): List<List<Int>> {
val result = mutableListOf<List<Int>>()
val hashIndex = hashMapOf<Int, MutableList<Int>>()
sample.forEachIndexed {index, number ->
if (hashIndex.containsKey(number)) {
val tempList = hashIndex[number]
tempList!!.add(index)
hashIndex[number] = tempList
} else {
hashIndex[number] = mutableListOf(index)
}
val diff = k - number
if (hashIndex.containsKey(diff)) {
val indexList = hashIndex[diff]
val firstIndex = indexList!!.first()
indexList.remove(firstIndex)
hashIndex[diff] = indexList
result.add(listOf(firstIndex, index))
}
}
return result
}
@Husseinhj
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment