Two Sum
The problem
Section titled “The problem”You get a list of integers and a target number. Exactly one pair of entries adds up to the target. Return the indices of that pair. You can’t use the same entry twice.
nums = [2, 7, 11, 15], target = 9 -> [0, 1] (2 + 7 = 9)Key insight
Section titled “Key insight”Brute force checks every pair, which is O(n²). The waste is that for each number you
re-scan the array looking for its partner, even though you know exactly what the partner
is: target - num.
So ask a different question as you walk the array once: have I already seen the partner of this number? A hash map from value to index answers that in O(1). If the partner is there, you’re done. If not, record the current number and move on.
Show solutionHide solution
def two_sum(nums: list[int], target: int) -> list[int]: seen = {} # value -> index where we saw it for i, num in enumerate(nums): if target - num in seen: return [seen[target - num], i] seen[num] = i return []export function twoSum(nums: number[], target: number): number[] { const seen = new Map<number, number>(); // value -> index where we saw it for (let i = 0; i < nums.length; i++) { const partner = seen.get(target - nums[i]); if (partner !== undefined) return [partner, i]; seen.set(nums[i], i); } return [];}import java.util.HashMap;import java.util.Map;
class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> seen = new HashMap<>(); // value -> index where we saw it for (int i = 0; i < nums.length; i++) { Integer partner = seen.get(target - nums[i]); if (partner != null) return new int[] {partner, i}; seen.put(nums[i], i); } return new int[0]; }}Complexity
Section titled “Complexity”- Time: O(n) — one pass, with an O(1) map lookup and insert per element.
- Space: O(n) — in the worst case the map holds every element before the pair is found.
Watch out for
Section titled “Watch out for”- Check before you insert. If you add the current number to the map first, an input
like
[3, 3]with target 6 still works, but[3, 2, 4]with target 6 would match 3 with itself. - Return indices, not values. That’s why sorting first doesn’t work directly: it destroys the original positions.
- Say the trade-off out loud. You are spending O(n) memory to drop from O(n²) to O(n) time. Interviewers want to hear that.
Variations
Section titled “Variations”Two Sum II - Input Array Is Sorted (LeetCode 167)
Section titled “Two Sum II - Input Array Is Sorted (LeetCode 167)”The array is sorted and you must use O(1) extra space. The trick: two pointers, one at each end. If the sum is too small move the left pointer right; if too big move the right pointer left. Sorted order guarantees you never skip the answer.
3Sum (LeetCode 15)
Section titled “3Sum (LeetCode 15)”Find all unique triplets that sum to zero. The trick: sort, fix one number, then run the sorted two-pointer Two Sum on the rest. Skip repeated values to avoid duplicate triplets. O(n²) overall.
Subarray Sum Equals K (LeetCode 560)
Section titled “Subarray Sum Equals K (LeetCode 560)”Count contiguous subarrays that sum to k. The trick: the same “have I seen the
partner?” idea applied to running totals. Keep a map of prefix-sum counts; at each
position, add the count of prefix - k seen so far.