How to find the two elements in a list whose sum is closest to zero in Kotlin

1 Answer

0 votes
fun findClosestToZero(arr: List<Int>) {
    if (arr.size < 2) {
        println("arr must have at least two elements.")
        return
    }

    // Step 1: Sort the arr
    val sortedArr = arr.sorted()

    var left = 0
    var right = sortedArr.size - 1
    var closestSum = Int.MAX_VALUE
    var closestPair = Pair(0, 0)

    // Step 2: Use two-indexed technique
    while (left < right) {
        val sum = sortedArr[left] + sortedArr[right]

        // Update closest sum and pair if needed
        if (kotlin.math.abs(sum) < kotlin.math.abs(closestSum)) {
            closestSum = sum
            closestPair = Pair(sortedArr[left], sortedArr[right])
        }

        // Move indexeds
        if (sum < 0) {
            left++ // Increase sum by moving left indexed
        } else {
            right-- // Decrease sum by moving right indexed
        }
    }

    // Output the result
    println("The two elements whose sum is closest to zero are: ${closestPair.first} and ${closestPair.second} with a sum of $closestSum.")
}

fun main() {
    val arr = listOf(23, -26, -88, -42, 55, 99, -11, 90, -13, 17, -31)
    
    findClosestToZero(arr)
}


/*
run:

The two elements whose sum is closest to zero are: -88 and 90 with a sum of 2.

*/

 



answered Sep 13, 2025 by avibootz
...