CodingNodes / Linked List / Find The Duplicate Number System design Space play · ←→ step · R restart

Problem

An array nums holds n + 1 integers, and every value is between 1 and n. Exactly one value appears more than once (it may appear three or more times). Return it.

Do not change the array, and use only a constant amount of extra memory. The trick is to read the array as a linked structure: from index i you step to index nums[i].

Constraints

  • 2 ≤ nums.length ≤ 100001 (that is n + 1 numbers)
  • 1 ≤ nums[i] ≤ n
  • Exactly one value is repeated

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(1)

Time: Both phases take a number of steps proportional to the length of the walk from index 0, and that walk has at most n + 1 distinct indexes.

Space: Only three integer variables are used. The array is only read, never changed.

Treat index i as pointing to index nums[i]. Since a value repeats, two indexes point to the same place, so the walk from 0 must enter a loop, and the repeated value is the entrance of that loop. Run a slow runner (one arrow per step) and a fast runner (two arrows) until they meet inside the loop. Then restart a second runner at index 0 and move it and slow one arrow at a time. They meet at the loop entrance, which is the duplicate.