AmazonEasyArray / Hash Map
Two Sum Variant
Software Engineer
Problem
Given an array of integers and a target value, find two numbers whose sum equals the target.
Example
Input: nums = [2, 7, 11, 15] target = 9 Output: [0, 1]
Approach
Use a hash map to store numbers that have already been visited. For every number, calculate target - currentNumber and check whether that value already exists in the hash map.
Complexity
Time: O(n)
Space: O(n)
Solution
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
return []
Related Topics
ArrayHash Map