Problem Statement
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Approach
sum = a + b\(\implies\)b = sum - a, whereais the current element.- Create a hash map to store
bas key and index ofaas value. - Iterate over the array in each iteration check if the current element is present in the hash map. If found, the index of it’s counterpart is already stored in the hash map.
- Else, store
band the current index in the hash map.
Solution in Swift
class Solution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var dict: [Int: Int] = [Int: Int]()
for (index, number) in nums.enumerated() {
if let firstPartIndex: Int = dict[number] {
return [firstPartIndex, index]
}
dict[target - number] = index
}
return []
}
}
Complexity
- Time Complexity: \(O(n)\)
- Space Complexity: \(O(n)\)