The problem. Given an array of integers nums and an integer target, return the indices of the two numbers that add up to target. Exactly one answer exists, and you may not use the same element twice.
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1] because nums[0] + nums[1] = 2 + 7 = 9
Input: nums = [3, 2, 4], target = 6
Output: [1, 2] 3 + 3 would be 6, but that uses index 0 twiceThe most direct idea: pick every index i, pair it with every later index j, and check whether the two values add up to target.
function twoSum(nums, target) { for (let i = 0; i < nums.length; i++) { for (let j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] === target) return [i, j]; } } return [];}Time O(n²), space O(1). There are about n²/2 pairs — 5 billion for 100,000 numbers. Notice what the inner loop is really doing: for a fixed nums[i], it is searching for one specific value, target - nums[i].
Searching is faster in sorted data. Sort the array, put left at the smallest value and right at the largest, and look at their sum:
left++.right--.One catch: the answer needs the original indices, and sorting moves the values. So instead of sorting nums, sort a list of indices by the value they point at.
function twoSum(nums, target) { // Indices ordered by value, so we can still report original positions. const order = nums.map((_, i) => i).sort((a, b) => nums[a] - nums[b]); let left = 0, right = order.length - 1; while (left < right) { const sum = nums[order[left]] + nums[order[right]]; if (sum === target) return [order[left], order[right]].sort((a, b) => a - b); if (sum < target) left++; else right--; } return [];}Time O(n log n), space O(n). The sort dominates; the pointer walk itself is only O(n). That's a huge improvement — but the sort is still work we only did to make searching cheap.
A hash map answers "have I seen this value, and where?" in O(1). So walk the array once. At each number, compute the partner it needs, need = target - nums[i], and ask the map whether we've already passed it. If yes, we're done. If not, store the current number so a later number can find it.
Storing after checking also takes care of the "don't use the same element twice" rule: when nums[i] looks for its partner, it isn't in the map yet.
Try a target that needs the last two numbers, or a pair of equal values like [3, 3].
Time O(n), space O(n). Every number is visited once and each map lookup is O(1) on average. We spend memory on the map to save time — the classic trade.
O(n²)About n²/2 pairs, each checked against the target.
O(1)Only two indexes.
O(n log n)[3, 3], target 6 returns [0, 1]. The first 3 is stored before the second one looks for it.[3, 2, 4], target 6 returns [1, 2], not [0, 0].[-3, 4, 3, 90], target 0 returns [0, 2].The sort dominates; the pointer walk is only O(n).
O(n)A sorted copy that remembers the original indexes.
O(n)Each number is visited once, with an O(1) average map lookup.
O(n)The map can store up to n numbers.