How to find the two elements in an array whose sum is closest to zero in Swift

1 Answer

0 votes
import Foundation

// Function to find the two elements whose sum is closest to zero
func findClosestToZero(_ arr: [Int]) {
    if arr.count < 2 {
        print("arr must have at least two elements.")
        return
    }

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

    var left = 0
    var right = sortedArr.count - 1
    var closestSum = Int.max
    var closestPair = (0, 0)

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

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

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

    // Output the result
    print("The two elements whose sum is closest to zero are: \(closestPair.0) and \(closestPair.1) with a sum of \(closestSum).")
}

let arr = [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
...