Two Sum
Difficulty: Easy · Pattern: Hashing · LeetCode #1
Given an integer array nums and an integer target, return the indices of the two different elements whose sum equals target, as [i, j] with i < j. Exactly one valid pair exists.
Example 1
text
nums = [5, 12, 3, 8], target = 11 → [2, 3] (3 + 8 = 11)Example 2
text
nums = [6, 6], target = 12 → [0, 1]Constraints: 2 ≤ nums.length ≤ 10⁴; exactly one answer exists.
Hints
- For each number x, the partner you need is
target − x. - Can you check whether that partner appeared earlier in O(1)?
- Store each value's index in a map after checking, so an element doesn't pair with itself.
Approach
Walk the array once with a map from value → index. At index j with value x, compute need = target − x. If need is already in the map at index i, then [i, j] is the answer (and i < j automatically). Otherwise record x → j and continue.
Checking before inserting handles duplicates correctly (e.g., [6, 6] with target 12).
Complexity
Time: O(n). Space: O(n) for the map.
Python solution
def twoSum(nums, target):
index_of = {}
for j, x in enumerate(nums):
need = target - x
if need in index_of:
return [index_of[need], j]
index_of[x] = j
return []JavaScript solution
function twoSum(nums, target) {
const indexOf = new Map();
for (let j = 0; j < nums.length; j++) {
const need = target - nums[j];
if (indexOf.has(need)) return [indexOf.get(need), j];
indexOf.set(nums[j], j);
}
return [];
}