AAlgoLoopSpaced repetition for LeetCode
MEDIUMFast & Slow PointersLeetCode ↗

Find the Duplicate Number

The key idea

Read each index i as a node pointing to node nums[i]. Because every value is in [1, n] and there are n + 1 slots, this functional graph must contain a cycle, and the entrance of that cycle is exactly the duplicated value. Floyd's tortoise-and-hare finds that entrance in O(1) space without altering the array.

Problem

You are given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.

There is only one repeated number in nums. Return *this* repeated number.

You must solve the problem without modifying the array nums and using only constant extra space.

Constraints

Examples

Input: nums = [1,3,4,2,2] Output: 2
Input: nums = [3,1,3,4,2] Output: 3
Input: nums = [3,3,3,3,3] Output: 3

Complexity

Time: O(n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Fast & Slow Pointers problems