What is Two Sum
Find two numbers that add to a target, and return their indices. Checking every pair is O(n²).
A hash map remembers each value as you scan, so the complement target − x is an O(1) lookup.
x, look up target − x. Do not pair an index with itself.value → index — O(n) time, O(n) space.nums = [2, 7, 11, 15], target = 9 → [0, 1] because nums[0] + nums[1] = 2 + 7 = 9
2 ≤ nums.length ≤ 10⁴ · -10⁹ ≤ nums[i] ≤ 10⁹
Approach
Try every possible pair of elements and check if they sum to the target. No extra memory needed — just nested loops.
i = 0).i, scan every element to its right (index j = i+1 to end).nums[i] + nums[j] == target.Why it's slow
For an array of length n, you check up to n × (n−1) / 2 pairs. With 10 elements that's 45 checks; with 100 it's 4,950. The inner loop repeats work already done — there's no memory of what you've seen.
Walk the array once. At each step, ask: "have I already seen the number I need?" Use a hash map to answer that in O(1).
value → index.nums[i] one by one (single pass).target − nums[i].nums[i] → i in the map and move on.Why it's fast
Each element is visited exactly once. The map lookup replaces the entire inner loop — instead of scanning backwards, you know in O(1) whether the complement exists. You trade O(n) space to eliminate O(n) repeated work.
Interactive Step-by-Step Visualizer
Algorithm & Pseudocode
Implementation