Question presented to candidate: "Given a list of integers, find a number that appears more than once. First solve it in general, then for the classic version โ n + 1 numbers, each between 1 and n, without modifying the list and with O(1) extra space. Please code it in Python."
What a strong answer should cover:
- Asking about the constraints first: value range, whether the list may be modified, the memory budget, one or several repeated values.
- The general answer: scan with a
set, return the first value already in it โ O(n) time, O(n) space. - The alternatives: sort and compare neighbours (O(n log n)), index negation (O(n), O(1) space, modifies the list), and Floyd's cycle detection on
i โ nums[i](O(n), O(1) space, read-only), with why the pigeonhole principle guarantees a duplicate. - Why Floyd works: two indices point to the duplicate, so it is the entrance of the cycle.
- Python specifics:
x in seenon asetis O(1) average but on alistis O(n);sorted()returns a copy whilelist.sort()mutates;len(set(nums)) != len(nums)for a yes/no; negative indices are valid in Python, so some index bugs are silent.
Clarifying questions expected:
- What is the value range? May I modify the list? How much extra space?
Code / implementation expected: Yes โ a set-based find_duplicate in Python, plus the Floyd version for the 1..n constraint.