Two Sum
One-pass hash map of value to index — look up the complement before inserting the current value.
2 min read
hash-map array
Problem#
Return indices of two numbers in nums that add up to target. Exactly one solution exists; you may not use the same element twice.
Examples#
nums=[2,7,11,15], target=9→[0,1].nums=[3,2,4], target=6→[1,2];nums=[3,3], target=6→[0,1].
Constraints#
2 <= nums.length <= 10^4,-10^9 <= nums[i] <= 10^9.
Approach#
One-pass hash map. For each index i, check whether target - nums[i] was seen previously; if so, return that index and i. Else store nums[i] → i.
Solution#
class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int,int> seen; for (int i = 0; i < (int)nums.size(); ++i) { auto it = seen.find(target - nums[i]); if (it != seen.end()) return {it->second, i}; seen[nums[i]] = i; } return {}; }};func twoSum(nums []int, target int) []int { seen := map[int]int{} for i, x := range nums { if j, ok := seen[target-x]; ok { return []int{j, i} } seen[x] = i } return nil}from typing import List
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: seen: dict[int, int] = {} for i, x in enumerate(nums): if target - x in seen: return [seen[target - x], i] seen[x] = i return []var twoSum = function(nums, target) { const seen = new Map(); for (let i = 0; i < nums.length; i++) { const complement = target - nums[i]; if (seen.has(complement)) return [seen.get(complement), i]; seen.set(nums[i], i); } return [];};class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> seen = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (seen.containsKey(complement)) { return new int[]{seen.get(complement), i}; } seen.put(nums[i], i); } return new int[0]; }}function twoSum(nums: number[], target: number): number[] { const seen = new Map<number, number>(); for (let i = 0; i < nums.length; i++) { const complement = target - nums[i]; if (seen.has(complement)) return [seen.get(complement)!, i]; seen.set(nums[i], i); } return [];}Editorial#
Looking up the complement before inserting the current value handles the “use the same element twice” trap — if the array had [3,3] and target 6, the second 3 looks up the first. Linear scan beats sort-and-two-pointer when you need original indices.
Complexity#
- Time:
O(n)average. - Space:
O(n).
Concept revision#
Related#