Created
March 13, 2020 20:56
-
-
Save tikipatel/8ffe12de0650b4df059c78f075240354 to your computer and use it in GitHub Desktop.
Daily Coder Problem March 13, 2020
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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