Practice · Linked list · 4 of 6

Find the Repeated Number

You are given nums, a list of n + 1 integers, each between 1 and n. There are more numbers than possible values, so some value must appear more than once. Here exactly one value does, though it may appear more than twice.

Return that repeated value. Don't change nums (no sorting it and no marking its entries), and use only a constant amount of extra memory, so no set or extra list.

Example 1

Input
nums = [2, 5, 1, 4, 3, 5]
Output
5
5 appears at positions 1 and 5.

Example 2

Input
nums = [4, 4, 4, 1, 4]
Output
4
The repeated value can appear more than twice, which leaves room for other values (2 and 3) to be missing.

Constraints

  • 1 ≤ n ≤ 10⁵, and nums holds n + 1 numbers.
  • Every number is between 1 and n.
  • Exactly one value appears two or more times; every other value appears at most once.