Optimal Python Solution for Two Sum (Interview Script)

2025-10-01

The Logic

  • A brute force approach checks all pairs and wastes time.
  • Use a hash map to track numbers already seen.
  • For each element, check whether its complement exists.

Implementation / Diagram

Key Invariant

At any index, the hash map contains all elements seen so far and their indices.

def twoSum(nums, target):
    seen = {}

    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            return [seen[complement], i]
        seen[num] = i