KatInterview

Locate Duplicate Integer with Strict Space Limit

Linked ListsAuto-graded · 19 test cases
HardAuto-gradedLinked Liststwo-pointersarrayslinked-list

Last updated

Find the single repeated value in an array of size n + 1 containing integers from 1 to n without altering the array or using extra space.

You are given a list nums containing $n + 1$ integers where every integer is between $1$ and $n$ inclusive. By the pigeonhole principle, at least one number in nums must appear more than once. The list contains exactly one value that repeats, though it may appear two, three, or more times.

Your task is to identify and return this repeated integer.

You must solve the problem under strict constraints:

  • You cannot modify the input array in any way (no sorting, swapping, or element sign flipping).
  • You must use only $O(1)$ constant extra space (no hash sets, hash maps, frequency arrays, or copies of the data).

Constraints

  • $1 \le n \le 10^5$
  • len(nums) $= n + 1$
  • $1 \le \text{nums}[i] \le n$ for all valid $i$
  • Exactly one number in nums is duplicated (occurring $\ge 2$ times).

Examples

Example 1

Input: find_repeated([4, 1, 3, 2, 4])

Output: 4

Example 2

Input: find_repeated([1, 1])

Output: 1

Example 3

Input: find_repeated([5, 2, 5, 1, 5, 3])

Output: 5

Hints

Hint 1

Consider treating the array as a directed graph or linked list where each index $i$ points to the index $\text{nums}[i]$.

Hint 2

Since values range from $1$ to $n$, every value is a valid index inside the array. Index $0$ is never pointed to by any value.

Hint 3

Using Floyd's cycle detection algorithm (tortoise and hare), locate the entrance to the cycle. The entrance node corresponds to the duplicate value.