Watch the hash map solution to Two Sum look up each number's complement first, then store it, finding the pair in one pass. O(n) time against brute force O(n²).
About this algorithm
Two Sum with a hash map finds two indices whose values add up to a target in one O(n) pass: for each value, look up its complement (target − value) among the values already seen, and if it is not there, store the value with its index and move on. The brute-force approach checks every pair in O(N²); the hash map turns each pair check into a single O(1) lookup, at the cost of O(n) extra space.
For each value x at index i, the answer is "did I previously see a value equal to target − x?". A hash map of value → index makes that lookup O(1). The first time the complement is present in the map, we have the pair.
Order matters. For each element x: (1) compute complement = target − x, (2) check if complement is already a key in the map, and if yes, return [seen[complement], i], (3) only AFTER the lookup, insert seen[x] = i. Inserting first would let the algorithm match an element with itself.
Brute force tries every pair (i, j), which is O(N²) comparisons. Trading O(N) extra space for the hash map collapses each pair check into a single O(1) lookup, so the whole pass is O(N).
The same value-to-index hash-map pattern shows up in problems like "subarray sum equals K" (prefix sums), "contains duplicate within k", and "longest substring without repeating characters". Whenever you need to ask "have I seen X before, and where?", a hash map is the right tool.