Hook
More breakout videos from this creator.
Can You Solve This Amazon Interview Question? Alright so today we're gonna solve two sum. 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. You can return the answer in any order. Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] = 9, we return [0, 1]. Example 2: Input: nums = [3,2,4], target = 6 Output: [1,2] Example 3: Input: nums = [3,3], target = 6 Output: [0,1] Constraints: 2 <= nums.length <= 10^4 -10^9 <= nums[i] <= 10^9 -10^9 <= target <= 10^9 Alright so for a first example we have the numbers 2, 7, 11 and 15 and our target is 9. So we know that 2 and 7 add up to 9. So we'll return 0 and 1. Example 2: we have 3, 2 and 4, our target is 6. So we would output 1 and 2. Example 3: we have 3 and 3 and our target is 6. So you're gonna return indices 0 and 1. Alright let's see how we're gonna solve it. We're gonna iterate through our array and hold on to the index as well. So first we're gonna create a hash map. seen = {} and this hash map needs to store our number and our index. {number, idx} seen = {} for i, curr_num in enumerate(nums): then we know that the number we're looking for is our target minus our current number. need = target - curr_num. Then if the number that we need is something we've already seen, we can just return those indices. if need in seen: return [seen[need], i] Otherwise we'll have to add our current number to the values we've already seen. seen[curr_num] = i Alright let's see if this works. Alright so there's our solution. Let me know if you passed this interview and comment down below if you have any questions. Follow for your daily Leetcode!