← Microsoft Interview Insights
The naive approaches all fail the constraints.
Start by clarifying the constraints and confirming that the array is read-only and that O(1) extra space and O(n) time are required. Then explain that this is a classic cycle detection problem, where the array values act as pointers to indices, and the duplicate value creates a cycle. Use Floyd's Tortoise and Hare algorithm to find the entrance of the cycle, which is the duplicate number.
Pro tip: Mention that this problem is equivalent to finding the start of a cycle in a linked list, and that the same algorithm can be applied. Also, note that while binary search on the value range is another approach, it requires O(n log n) time, so Floyd's algorithm is optimal.
Confirm that the array is read-only, that values are in 1..n, and that exactly one duplicate exists. Discuss edge cases like n=1 or duplicate at the start.
Explain that each element points to the index equal to its value, forming a linked list with a cycle. The duplicate value is the entry point of the cycle.
Use two pointers: slow moves one step, fast moves two steps. They meet inside the cycle. Then reset slow to start and move both one step until they meet again; that meeting point is the duplicate.
State that time is O(n) and space is O(1). Compare with other approaches like sorting (O(n log n)) or using a hash set (O(n) space), highlighting why this is optimal.
Walk through a small example (e.g., [1,3,4,2,2]) to demonstrate the algorithm and verify correctness.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.