Created
February 27, 2026 16:32
-
-
Save odrianoaliveira/0e7ced9bdb261d7f9ff83ebb57b81c8c to your computer and use it in GitHub Desktop.
Two Sum kotlin solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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