As asked
Given an array of integers and a target value, return the indices of the two numbers that add up to the target. You may not use the same index twice. Now: can you do it in O(n) time? And if memory is extremely tight, what is the best space complexity you can achieve?
Sample answer outline
O(n) time with a hash map, O(n) space. For the space-constrained version, a sorted array plus two pointers gives O(n log n) time and O(1) space, but requires the original indices to be stored alongside values. A strong answer explains the trade-off clearly: sorting destroys original indices unless you save them, and O(1) space means O(n log n) time. Interviewers often follow up to force the candidate to articulate why they cannot do better than O(n) time with O(1) space for the general case.
Reference implementation (python)
def two_sum(nums: list[int], target: int) -> list[int]:
seen = {} # value -> index
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []Expect these follow-ups
- What if the array were already sorted?
- What if you needed to return all pairs, not just one?