We use a hash map (dictionary in Python) to store the value and its index as we iterate through the array. For each number, we calculate the complement (target - current_number). If the complement is already in our map, it means we found the pair.
- Initialize an empty dictionary
seen. - Iterate through the array using
enumerateto get both indexiand valuenum. - Calculate
complement = target - num. - Check if
complementexists inseen. - If it exists, return
[seen[complement], i]. - Otherwise, add the current
numtoseenwith its index:seen[num] = i.
- Time Complexity: O(N), where N is the number of elements in the array. We traverse the list only once.
- Space Complexity: O(N), as we store at most N elements in the hash map.
def solve(nums, target):
# Dictionary to store value: index
seen = {}
for i, num in enumerate(nums):
complement = target - num
# If complement is found, return the indices
if complement in seen:
return [seen[complement], i]
# Store index of the current number
seen[num] = i
return [] # Should not reach here based on problem constraints