Why a hash map turns Two Sum into one pass, and what sorting first buys you.
About this comparison
Three lanes hold the same seven numbers, 58, 7, 92, 31, 44, 82 and 18, and look for two that add up to 100. Each lane does one comparison or one lookup per beat, so the finishing order is the work each one needed.
Brute force tries every pair with two loops: 58 with each number after it, then 7, and so on. It needs no extra memory, but the pairs grow with the square of n, O(n²).
Sort plus two pointers sorts the row first: 7, 18, 31, 44, 58, 82, 92. A pointer starts at each end. A sum that is too small moves the left pointer up; one that is too big moves the right pointer down. Each sum rules out one number, so after the O(n log n) sort it is one pass.
The hash map reads the numbers once. For each one it asks whether its partner, 100 minus the number, is already stored, and stores the number if not. A lookup is O(1) on average, so the pass is O(n), paid for with O(n) memory.
Brute force spends time, the hash map spends memory, and two pointers spend a sort. Sorting also loses the original positions, so returning indices, as the interview problem asks, means sorting each value with its index.
The only pair is the last two numbers, 82 and 18: brute force's worst case, all 21 pairs. The hash map looks 7 times, from 58 needs 42, not seen, to 18 needs 82, stored one beat earlier. Two pointers finish first: 7 + 92 = 99 is too small, 18 + 92 = 110 too big, then 18 + 82 = 100.
The sort is drawn as one beat, which hides real work: cheap on seven numbers, but on a large input the sort outgrows the hash map's single pass.
Use the hash map for Two Sum as it is usually asked: unsorted numbers, return the indices, one pass. Use two pointers when the array is already sorted or memory is tight: no sort to pay, O(1) extra space, and the same walk solves three sum. Brute force is fine for a handful of numbers, and as a first draft to test the others against.