Question presented to candidate: "Given a list of integers and a target, return the indices of the two numbers that add up to the target. You can assume there is exactly one answer and you cannot use the same element twice. Please code it in Python and tell me the time and space complexity."
What a strong answer should cover:
- The brute force first (check every pair, O(nยฒ)), then the improvement: for each
x, look up its complementtarget - x. - A one-pass
dictmapping value โ index, with the lookup done before the insert so an element never pairs with itself. - O(n) average time and O(n) extra space, and why "average":
dictlookups are O(1) on average, not in the worst case. - The sorted-input alternative: two pointers, O(n) time and O(1) space, and why sorting loses the original indices.
- Python specifics:
enumeratefor index + value,inon adictis a hash lookup (on alistit is a linear scan), and Python ints never overflow.
Clarifying questions expected:
- Indices or values? Is the input sorted?
- What should happen when there is no pair?
Code / implementation expected: Yes โ a two_sum(nums, target) function in Python using a dict, run on a few inputs including duplicates and a no-answer case.