Arrays and Iteration
Two-Sum with Hash Lookup
Walk the array once, storing seen values in a lookup table. When the complement is already present, the result indices are known.
Algorithm
Basic Implementation
basic.swift
let arr = [2, 7, 11, 4, 5]
let target = 9
var seen: [Int: Int] = [:]
var first = -1
var second = -1
for i in 0..<arr.count {
let value = arr[i]
let need = target - value
if let j = seen[need] {
first = j
second = i
break
}
seen[value] = i
}
print("[\(first), \(second)]")
Complexity
- Time: O(n) average
- Space: O(n)
Implementation notes
- Swift infers
arras[Int]fromlet arr = [2, 7, 11, 4, 5]; the array andtargetbindings are immutable. var seen: [Int: Int] = [:]is a mutable dictionary from value to prior index.firstandsecondare mutableIntsentinels initialized to-1and are replaced only after a complement hit.- The loop uses
for i in 0..<arr.count, readslet value = arr[i], and computeslet need = target - value. - Dictionary lookup uses optional binding:
if let j = seen[need]. On a miss, the optional isnil; on a hit,jis the stored prior index. - The code writes
seen[value] = ionly after checking the complement, so an element cannot pair with itself at the same index. - The trace records an initial miss for
need=7and map state{2: 0}, then a hit ati=1withneed=2, producing result[0, 1]. print("[\(first), \(second)]")formats the two sentinel/result values and prints[0, 1].
execution replay
The checked-in replay follows the language-neutral state table for `array-two-sum-hash`.
cross-language comparison
This Swift DSA version keeps the same data and final output as every other DSA book in this wave.