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

1 Answer

0 votes
import Foundation

func twoSum(_ arr: [Int], target: Int) -> (Int, Int)? {
    for i in 0..<arr.count {
        for j in i + 1..<arr.count {
            if arr[i] + arr[j] == target {
                return (i, j) // Return tuple with indices
            }
        }
    }
    return nil // Return nil if no match found
}

let array1 = [1, 5, 7, 4, 3, 2]
let array2 = [3, 1, 4, 2, 5]

// Finding pairs
if let (i, j) = twoSum(array1, target: 9) {
    print("Indices: (\(i), \(j)), Numbers: (\(array1[i]), \(array1[j]))")
} else {
    print("No matching pair found.")
}

if let (i, j) = twoSum(array2, target: 8) {
    print("Indices: (\(i), \(j)), Numbers: (\(array2[i]), \(array2[j]))")
} else {
    print("No matching pair found.")
}




/*
run:

Indices: (1, 3), Numbers: (5, 4)
Indices: (0, 4), Numbers: (3, 5)

*/

 



answered May 22, 2025 by avibootz
...