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 you may not use the same element twice.
Example: nums = [2, 7, 11, 15], target = 9 → [0, 1]
Brute force: Check every pair (i, j) until one sums to the target. (time O(n²), space O(1))
No visualization loaded.
Watch
—
i
Press Run to begin.
0/0
Why the best approach wins
Brute force re-checks the same region over and over — O(n²) comparisons. The hash map trades a little memory for speed: by remembering what it has seen, each element is examined once, turning O(n²) into a single O(n) pass.
Brute force: O(n²) time / O(1) spaceHash map (one pass): O(n) time / O(n) space
Your turn — implement twoSum
Loading editor…