Use a hash map to store each number's index while iterating through the array. For each element, calculate its complement (target - num). If the complement is already in the map, return the pair of indices in O(n) time.
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
seen = {}
for i, num in enumerate(nums):
diff = target - num
if diff in seen:
return [seen[diff], i]
seen[num] = i
return []
class Solution {
public int[] twoSum(int[] nums, int target) {
Map seen = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int diff = target - nums[i];
if (seen.containsKey(diff)) {
return new int[] { seen.get(diff), i };
}
seen.put(nums[i], i);
}
return new int[] {};
}
}