Optimal Approach & Code:
- Use a Hash Map to store numbers and their indices, enabling O(1) complement lookups.
def two_sum(nums: list[int], target: int) -> list[int]:
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []
Complexity & Key Logic:
- Time Complexity: O(N) single-pass traversal over the array.
- Space Complexity: O(N) to store seen elements in the hash map.
- Algorithm Details:
- For each element, calculate the needed complement (target - num).
- Check if the complement already exists in our dictionary.
- If found, return the complement's stored index and the current index immediately.
- Otherwise, insert the current number and index into the map.