Takeaways:
- HashMaps for Lookup
- O(1) time complexity because it’s a real-time operation
- Single-Pass Iteration/Prefix-Sum
- Important to follow the process:
- Think about the problem (15-20s)
- Ask any immediate clarifying questions
- Write out test cases (these should encompass best-case, average-case, worst-case)
- If you think of any more questions refer to Step 2
- Write out algorithm
- Write out pseudocode (optional)
- Write code
- Optimize if possible
- Hash Map/Frequency Counter
O(n) Solution
class Solution(object):
def twoSum(self, nums, target):
empty_map = {}
for i, num in enumerate(nums):
complement = target - num
if complement in empty_map:
return [empty_map[complement], i]
empty_map[num] = iAlgorithm:
- Initialize an empty
hashmap - Iterate through the list of nums using
enumerate- This allows for tracking of the current number (
num) alongside the index of the current number (i)
- This allows for tracking of the current number (
- Instantiate a variable
complementand set it equal totarget-num - If this complement is in the hashmap (not nums), return the index of
complementandi
Test Case:
Let’s take an example where nums = [1, 2, 4, 6] and target = 10
i = 0andnum = 1complement = 10 - 1 = 99isn’t in the hashmap as the hashmap is initialized empty, so it gets added toempty_mapas{ 1 : 0 }
i = 1andnum = 2complement = 10 - 2 = 88isn’t in the hashmap, so it gets added toempty_mapas{ 2 : 1}
i = 2andnum = 4complement = 10 - 4 = 66isn’t in the hashmap, so it gets added toempty_mapas{ 4 : 2}
i = 6andnum = 3complement = 10 - 6 = 44is in the hashmap, so it returnsempty_map[4], which is2, andi, which is3, revealing the answer of[2,3]