PracticeNeetCode ↗LeetCode ↗
Given an array of integers nums and an integer target, return the indices of the two numbers that add up to target. Each input has exactly one solution, and the same element can't be used twice.
target - n) before inserting the current number.seen.i, value n in nums: compute complement = target - n.complement is already a key in seen, return [seen[complement], i].seen[n] = i and continue.Time: O(n) — Space: O(n)
def twoSum(nums: list[int], target: int) -> list[int]:
seen = {}
for i, n in enumerate(nums):
complement = target - n
if complement in seen:
return [seen[complement], i]
seen[n] = i
return []How the solution above works, piece by piece.
seen = {} maps each number already visited to its index.for i, n in enumerate(nums): one pass, with both index and value.complement = target - n: the partner this number needs.if complement in seen: the partner was visited earlier, so return both indices: the earlier one from the map and the current i.seen[n] = i: store the current number after the check, so a number can't pair with itself. One pass: O(n) time, O(n) space, instead of O(n²) for checking every pair.Running it on nums = [2, 7, 11, 15], target = 9:
[0, 1] after only two steps.Striver (takeUforward) — 2 Sum Problem, Brute-Better-Optimal