We use a hash map to store the values we've seen so far and their indices. For each number x, we check if target - x is already in the map.
- Initialize
seen = {}. - Iterate through
numswith indexi:complement = target - nums[i].- If
complementis inseen, return[seen[complement], i]. - Otherwise,
seen[nums[i]] = i.
- Time Complexity: O(N).
- Space Complexity: O(N).
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i