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
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![Animated sliding window over the array [2, 1, 5, 1, 3, 2]: a three-number window adds the new number and subtracts the old one, showing sums 8, 7, 9 and 6 and a maximum of 9.](https://i.ytimg.com/vi/NM5paB6_7wg/maxresdefault.jpg)


