Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

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
...