How do you solve the Two Sum problem, and what is the complexity of your approach?
The efficient approach is a single pass with a hash map. As you walk the array, ask a simple question: have I already seen the number that would complete the pair? Store each value and its index as you go, and check for the complement before you store the current value, which guarantees you never reuse the same element twice.
def two_sum(nums, target):
seen = {}
for i, value in enumerate(nums):
complement = target - value
if complement in seen:
return seen[complement], i
seen[value] = i
return None
print(two_sum([2, 7, 11, 15], 9))
print(two_sum([3, 2, 4], 6))The outputs are the index pairs zero and one, and one and two. The second example is the one that catches people: the pair is three plus three is not it, but two plus four is, so the correct answer is indices one and two rather than the naive pairing of the first three with the four.
The mechanism is what makes it linear rather than quadratic. A brute force approach tries every pair and costs O of n squared. The map replaces the inner search with a constant-time lookup, so each element is visited once and the total is O of n time with O of n space.
The trade-off to name is that you pay in memory for the speed, and you give up the sorted-input shortcut that lets you solve it in O of 1 extra space. Also note the ordering rule: because you check for the complement before inserting the current value, you can never return the same index twice, which matters when the target is twice a single element, for example two plus two equals four.