Skip to content

Instantly share code, notes, and snippets.

@IhwanID
Last active February 1, 2024 13:00
Show Gist options
  • Save IhwanID/bf4dbe52528dd43960adb5b445d9f8a2 to your computer and use it in GitHub Desktop.
Save IhwanID/bf4dbe52528dd43960adb5b445d9f8a2 to your computer and use it in GitHub Desktop.
Given a set of numbers, determine if there is a pair that equals a given sum.
//func hasPairWithSum(_ arr: [Int], _ sum: Int) -> Bool {
//
// for i in 0..<arr.count {
// for j in i + 1..<arr.count {
// if arr[i] + arr[j] == sum {
// return true
// }
// }
// }
// return false
//}
func hasPairWithSum(_ arr: [Int], _ sum: Int) -> Bool {
var comp = Set<Int>()
for value in arr {
if comp.contains(value) {
return true
}
comp.insert(sum-value)
}
return false
}
hasPairWithSum([1,2,4,9], 8) //false
hasPairWithSum([1,2,4,4], 8) //true
hasPairWithSum([1,2,5,3], 8) //true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment