Skip to content
Interview

Interview

Two Sum Interview Question: One-Pass Hash Map Solution in Python

· Two Sum interview question in Python | sirf ek pass mein O(n)

Solve Two Sum in one pass: keep a Python dict of the numbers you have seen and, for each new number, look up what it still needs (target minus number). The O(n²) brute force becomes an O(n) hash map solution. A classic coding interview question.

The code

solution
def two_sum(nums, target):
    seen = {}
    for i, x in enumerate(nums):
        if target - x in seen:
            return [seen[target - x], i]
        seen[x] = i
Interview SheetTwo Sum, explained in fullThe idea, the steps, the complexity and the code in four languages, plus the rest of the Hashing pattern.