Question presented to candidate: "Explain the two-pointer technique. Then, in Python, use it to find two numbers in a sorted list that add up to a target, and tell me how it beats the obvious nested loop."
What a strong answer should cover:
- Two indices moving through the data under a rule; the two shapes (converging from both ends, and same-direction read/write).
- Why moving a pointer is safe: the sorted (monotonic) order lets one comparison rule out a whole element.
- O(n) time and O(1) extra space versus O(nยฒ) for checking every pair; sorting first adds O(n log n).
- When a hash map is the better tool (unsorted input, original indices needed).
- Python specifics: tuple swap
a[i], a[j] = a[j], a[i],len(arr) - 1is -1 for an empty list so the loop simply does not run, and avoiding slices likearr[1:]inside the loop because each one copies.
Clarifying questions expected:
- "Is the list sorted, and can it contain duplicates or negative numbers?"
- "Should I return indices or values, and what if no pair exists?"
Code / implementation expected: Yes โ a Python pair_sum(arr, target) with left/right indices, plus a same-direction example such as removing duplicates in place.