What better way to start our Leetcode adventure than with the classic Two Sum problem. The Problem is as follows: "Given an array of integers and an integer target, return indicies of the two numbers such that they add up to a target".
The problem can be sovled in O(n) time complexity by iterating over the nums and adding seen numbers to a hashmap for 0(1) lookup. The algorithm will work as follows: 1. Create a hash map to store seen values map[value]index. 2. Iterate over nums, calculate the difference between the target and the current value. 3. If the difference is in our hashmap return the values otherwise add the value to the hashmap.
func twoSum(nums []int, target int) []int {
hashMap := make(map[int]int)
first := 0
second := 0
for i := range len(nums) {
diff := target - nums[i]
_, prs := hashMap[diff]
if prs == true {
first = hashMap[diff]
second = i
break
} else {
hashMap[nums[i]] = i
}
}
return []int{first, second}
}