Given an array of integers nums and an integer target, return indices of the two numbers that add up to target. Each input has exactly one solution and you may not use the same element twice.
For every number x we encounter, we need to know if (target - x) has already been seen. A HashMap gives us O(1) lookup ā so instead of checking every pair (O(n²)), we do a single pass storing each number's index, checking for its complement at every step.
Check every pair (i, j) where i ā j. Return when nums[i] + nums[j] === target. Too slow for large inputs.
Initialize an empty hashmap. For each index i, compute complement = target - nums[i]. If complement is already in the map, return [map[complement], i]. Otherwise, store nums[i] ā i in the map and continue.
We iterate through the array once ā O(n). The hashmap stores at most n elements ā O(n) space. Each lookup and insert is O(1) average.
def twoSum(self, nums: List[int], target: int) -> List[int]:
seen = {} # value -> index
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return [] # guaranteed to have solutionWhat pattern do you think this problem uses?