FresherFresher (0–1 yrs)CodingPythonAmazonGoogleMicrosoft
Two Sum coding interview
Solve Two Sum: return indices of two numbers that add to target. Explain time/space and edge cases.
Answers use simple, clear English.
Audio N/ATime: O(n)Space: O(n)
Quick interview answer
One-pass hash map: for each value store index; look up target-x before inserting. O(n) time, O(n) space. Edges: duplicates, no solution, negative numbers, empty array.
Detailed answer
One-pass hash map: for each value store index; look up target-x before inserting. O(n) time, O(n) space. Edges: duplicates, no solution, negative numbers, empty array. Prefer indices not values when asked. Alternative: sort + two pointers loses original indices unless you track them.
Real example & use case
Promo engine: find two cart lines totaling gift-card amount.
Pros & cons
Pros: optimal average. Cons: extra memory vs sorted two-pointer.
Code example
def two_sum(nums: list[int], target: int) -> list[int]:
seen: dict[int, int] = {}
for i, x in enumerate(nums):
need = target - x
if need in seen:
return [seen[need], i]
seen[x] = i
raise ValueError('no pair')Practice code · python (view only · no execution)
def two_sum(nums: list[int], target: int) -> list[int]:
seen: dict[int, int] = {}
for i, x in enumerate(nums):
need = target - x
if need in seen:
return [seen[need], i]
seen[x] = i
raise ValueError('no pair')#dsa#hashmap#two-sum