All problems

Problem 26

Find the Duplicate Number

Medium · 20 pts · Array, Two Pointers

Problem

An array has N + 1 integers, and each of them is between 1 and N inclusive. Since there are more elements than possible values, at least one value must repeat. In this problem exactly one value is repeated, though it may appear two or more times. Find that value. A hash set finds it easily. For a challenge, try it without extra memory: treat each value as a pointer to the next index and use Floyd's cycle detection, because the repeated value is where the cycle begins.

Input

First line: integer N. Second line: N + 1 space-separated integers.

Output

Print the repeated value.

Constraints

1 <= N <= 100000; 1 <= A[i] <= N; exactly one value is repeated

Example input

4
1 3 4 2 2

Example output

2

Explanation

The array is 1 3 4 2 2 with N = 4. Every value from 1 to 4 appears once except 2, which appears twice, so the answer is 2.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Missing Number Next: Majority Element