Question presented to candidate: "Given an array of integers, find all unique triplets that sum to zero. Each triplet should appear only once in the output, even if the array has duplicates. Please write it in Python and tell me the time and space complexity."
What a strong answer should cover:
- Brute force is three nested loops, O(n³); the expected solution sorts first and then, for each anchor, runs a two-pointer scan: O(n²) time.
- Why moving a pointer is safe on a sorted array: a too-small sum means the left value can never work with this anchor, a too-big sum means the right value cannot.
- Duplicate handling by skipping equal neighbours (anchor and middle), instead of a set of results.
- Early exit when the anchor is positive, and edge cases: fewer than three elements, all zeros.
- Python specifics:
sorted()returns a new list (the caller's list stays untouched) whilelist.sort()sorts in place; lists are unhashable, so a set-based dedupe needs tuples; Python integers never overflow.
Clarifying questions expected:
- "Do you want values or indices?" — sorting loses the original indices.
- "Must each distinct triplet appear once, and may I sort the input in place?"
Code / implementation expected: Yes — a three_sum(nums) function in Python that sorts once and runs a two-pointer scan per anchor.