Skip to content

Instantly share code, notes, and snippets.

@odrianoaliveira
Created February 27, 2026 16:32
Show Gist options
  • Select an option

  • Save odrianoaliveira/0e7ced9bdb261d7f9ff83ebb57b81c8c to your computer and use it in GitHub Desktop.

Select an option

Save odrianoaliveira/0e7ced9bdb261d7f9ff83ebb57b81c8c to your computer and use it in GitHub Desktop.
Two Sum kotlin solution
// input..: [1,6,10]
// target.: 16
// output.: [1,2]
fun main() {
val array = arrayOf(1, 6, 10)
val target = 16
val result = twoInt(array, target)
assert(result == Pair(1,2))
println(result)
val result2 = twoInt(arrayOf(3, 3), 6)
assert(result2 == Pair(0,1))
println(result2)
}
fun twoInt(array: Array<Int>, target: Int): Pair<Int,Int> {
val positions: MutableMap<Int,Int> = mutableMapOf() // num to idx
for ( (i, v) in array.withIndex()) {
val complement = target - v
if (positions.contains(complement)) {
val compPos = positions[complement]!!
return Pair(compPos,i)
}
positions.put(v, i)
}
throw Exception("there is no solution")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment