Example 1
- Input
- nums = [1, 3, 4, 2, 2]
- Output
- 2
The value 2 appears twice, so the answer is 2.
You are given an array of n plus one integers drawn from one to n with exactly one repeated value. Return the repeated number without modifying the array and with constant extra space.
Given an integer array nums of length , whose values are between and inclusive, return the only distinct value that occurs more than once. That value may occur more than twice; some other values may be absent.
The required solution must leave the array unchanged and use constant extra space. The hash-set approach below is a teaching baseline that relaxes the space requirement; the optimal approach satisfies both requirements.
nums has elements.The value 2 appears twice, so the answer is 2.
Value 3 occurs at two different positions. Following links from index 0 gives 0 → 3 → 4 → 2 → 3, whose loop entrance is 3.
Only the distinct value 3 repeats, although it occurs five times. Values 1, 2 and 4 may be absent. The walk 0 → 3 → 3 enters a self-loop at the repeated value.
The smallest valid array has two entries but only one allowed value. Both entries are 1; the implicit walk enters the self-loop at index 1.
Treat each array index as a node and its stored value as the index of the next node. Example 1 produces the walk 0 → 1 → 3 → 2 → 4 → 2, so the walk enters a loop at index 2. Index 0 cannot be revisited because no value is zero. The first loop node has two incoming links, making its index the repeated value. Floyd's slow and fast pointers find that entrance using only index variables and reads from the array.
Reveal Hash Set: intuition, complexity, and code
i as a node whose next node is nums[i]: with n + 1 values in [1, n], two nodes share a target and a cycle is guaranteed.When values fall inside the index range, follow them as links: a forced cycle turns array duplicates into a linked-list entrance hunt.