Python
Junior (0–2 yrs)
Coding
Very frequent
Python
Two Sum
hash map
arrays
LeetCode
Two Sum in Python — return indices of two numbers that add to a target
py-jun-005
Your answer
Answer as you would in a real interview — explain your thinking, not just the conclusion.
Log in to save progress.
Model answer
Iterate with enumerate, compute complement = target - num, and check if complement is in a dict we've been building. If yes, return [seen[complement], current index]. Dicts in CPython are hash maps so lookup is O(1) average. Overall complexity: O(n) time, O(n) space. Brute force with nested loops is O(n²) — always explain the trade-off.
Code example
from typing import Optional
def two_sum(nums: list[int], target: int) -> Optional[list[int]]:
seen: dict[int, int] = {} # value -> index
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return None
# Tests
print(two_sum([2, 7, 11, 15], 9)) # [0, 1]
print(two_sum([3, 2, 4], 6)) # [1, 2]
print(two_sum([3, 3], 6)) # [0, 1]
# Sorted array variant (O(1) space with two pointers)
def two_sum_sorted(nums: list[int], target: int) -> list[int]:
lo, hi = 0, len(nums) - 1
while lo < hi:
s = nums[lo] + nums[hi]
if s == target:
return [lo, hi]
elif s < target:
lo += 1
else:
hi -= 1
return []
Follow-up
How would you handle the case where the same element cannot be used twice (e.g., if the array is [3, 3] and target is 6)?