Two Sum: Why a Hash Map Turns an O(n²) Interview Problem Into O(n)
Two Sum asks for the indexes of two numbers in a list that add up to a given target, and it is one of the most frequently asked coding interview questions. The obvious brute-force approach checks every pair, which scales quadratically and becomes very slow on large inputs. A faster method reframes the problem: for each number, it checks whether the complement it needs has already been seen, using a dictionary for constant-time lookups. Storing each value only after checking for its complement prevents a number from pairing with itself. The author reports that this single-pass version ran roughly 1,800 times faster than brute force on a test input, and the advantage grows as the list gets longer.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in