Find the Duplicate Number

Medium

Topics
ArrayTwo PointersBinary Search

Given an array nums of n+1 integers where each value is in [1, n], exactly one value is repeated. Return the repeated number without modifying the array and using O(1) extra space.

Example 1

1031422324
Reading i → nums[i] as a pointer makes the array a linked list, and a repeated value is a node with two things pointing at it — the entry to a cycle. The duplicate is 2.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [1,3,4,2,2]
Output: 2

Example 2

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

Constraints

  • 1 <= n <= 10^5
  • nums.length == n + 1
  • Only one repeated number, but it may appear more than once.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Because values lie in [1, n], treat each value as a "next index" pointer. Following these pointers must eventually cycle, and the entrance to the cycle is the duplicate.

Floyd’s tortoise-and-hare finds that cycle entrance in O(1) space, without altering the array.

Approach

  1. Phase 1: advance slow by one and fast by two until they meet inside the cycle.
  2. Phase 2: reset slow to the start; move both one step at a time. Where they meet is the cycle entrance = the duplicate.

Walkthrough

nums = [1,3,4,2,2]
follow indices -> a cycle forms at value 2
Floyd meeting + reset lands on 2 -> answer 2

Complexity

  • Time — O(n): both phases traverse a linear number of steps.
  • Space — O(1): two pointers, array untouched.

Common Pitfalls

  • Sorting or a hash set are simpler but violate the O(1)-space / read-only constraints.

Full Solution — all languages

class Solution:
    def findDuplicate(self, nums):
        slow = fast = nums[0]
        while True:
            slow = nums[slow]
            fast = nums[nums[fast]]
            if slow == fast:
                break
        slow = nums[0]
        while slow != fast:
            slow = nums[slow]
            fast = nums[fast]
        return slow
SensAI
Beta
Tap the mic to stop voice mode