Two Sum
Two Sum
Problem: Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
Solution
def two_sum(nums, target):
= {}
seen for i, num in enumerate(nums):
= target - num
complement if complement in seen:
return [seen[complement], i]
= i
seen[num] return []
# Example
= [2, 7, 11, 15]
nums = 9
target print(two_sum(nums, target)) # [0, 1]
Analysis
Time Complexity: O(n)
Space Complexity: O(n)
Approach
- Hash Map Approach: Use a hash map to store numbers we’ve seen
- One Pass: For each number, check if its complement exists in the map
- Return Indices: Return the indices when complement is found
Edge Cases
- Empty array
- No solution exists
- Duplicate numbers
- Array with single element
Variations
- Two Sum II (Sorted Array): Use two pointers approach
- Three Sum: Extend to find three numbers
- Four Sum: Extend to find four numbers