Problem Description
Given an array of n+1 integers where each integer is in the range [1, n] inclusive, there is only one repeated number present in the array. The goal is to find and return this duplicate number without modifying the array and using only constant extra space.
Key Insights
- Since there are n+1 elements with values only from 1 to n, by the pigeonhole principle at least one number must be repeated.
- The problem can be approached by mapping the array values to indices, forming a cycle structure.
- Floyd’s Tortoise and Hare algorithm (cycle detection) can be applied to find the duplicate number in linear time and constant space.
- There is no need for extra data structures like hash sets or alterations to the original array, satisfying the space and array-modification constraints.
Space and Time Complexity
Time Complexity: O(n) Space Complexity: O(1)
Solution
The solution leverages Floyd's Tortoise and Hare cycle detection algorithm. Think of each array element as a pointer to another index, forming a linked list with a cycle (the duplicate number creates the cycle). The algorithm works in two phases:
- Detect a meeting point within the cycle by having two pointers (tortoise and hare) move at different speeds.
- Find the cycle entrance by resetting one pointer to the start and moving both pointers at the same speed. The meeting point reveals the duplicate number.
This approach provides an elegant solution that satisfies both linear runtime and constant space requirements.