Skip to content

Instantly share code, notes, and snippets.

@tikipatel
Created March 13, 2020 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tikipatel/8ffe12de0650b4df059c78f075240354 to your computer and use it in GitHub Desktop.
Save tikipatel/8ffe12de0650b4df059c78f075240354 to your computer and use it in GitHub Desktop.
Daily Coder Problem March 13, 2020
/*
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can you do this in one pass?
*/
let testArray = [10, 15, 3, 7]
let testTarget = 17
enum TargetResult {
case notFound
case found(index1: Int, index2: Int)
}
func doesTarget(_ target: Int, existIn array: [Int]) -> TargetResult {
var complementMap: [Int: Int] = [:]
for (index, i) in array.enumerated() {
let complement = target - i
if let complementIndex = complementMap[complement] {
return .found(index1: index, index2: complementIndex)
}
complementMap[i] = index
}
return .notFound
}
print(doesTarget(testTarget, existIn: testArray))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment