How to implement the two sum algorithm to find two values in array that add up to target with Kotlin

1 Answer

0 votes
fun twoSum(arr: IntArray, target: Int): Pair<Int, Int>? {
    for (i in arr.indices) {
        for (j in i + 1 until arr.size) {
            if (arr[i] + arr[j] == target) {
                return Pair(i, j) // Return indices as a Pair
            }
        }
    }
    return null // Return null if no match found
}

fun main() {
    val array1 = intArrayOf(1, 5, 7, 4, 3, 2)
    val array2 = intArrayOf(3, 1, 4, 2, 5)

    twoSum(array1, 9)?.let { (i, j) ->
        println("Indices: ($i, $j), Numbers: (${array1[i]}, ${array1[j]})")
    } ?: println("No matching pair found.")

    twoSum(array2, 8)?.let { (i, j) ->
        println("Indices: ($i, $j), Numbers: (${array2[i]}, ${array2[j]})")
    } ?: println("No matching pair found.")
}


 
/*
run:
 
Indices: (1, 3), Numbers: (5, 4)
Indices: (0, 4), Numbers: (3, 5)
 
*/

 



answered May 22, 2025 by avibootz
...