Find the Duplicate Number in an Array

Problem

An array of n+1 integers contains numbers from 1 to n, with exactly one number repeated. Find that duplicate without modifying the array or using extra space (Floyd's Cycle Detection on indices).

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

Python Solution

def find_duplicate(nums):
    slow = fast = nums[0]
    while True:
        slow = nums[slow]
        fast = nums[nums[fast]]
        if slow == fast:
            break
    slow2 = nums[0]
    while slow != slow2:
        slow = nums[slow]
        slow2 = nums[slow2]
    return slow

C++ Solution

int findDuplicate(vector<int>& nums) {
    int slow = nums[0], fast = nums[0];
    do {
        slow = nums[slow];
        fast = nums[nums[fast]];
    } while (slow != fast);

    int slow2 = nums[0];
    while (slow != slow2) {
        slow = nums[slow];
        slow2 = nums[slow2];
    }
    return slow;
}

Java Solution

class Solution {
    public int findDuplicate(int[] nums) {
        int slow = nums[0], fast = nums[0];
        do {
            slow = nums[slow];
            fast = nums[nums[fast]];
        } while (slow != fast);

        int slow2 = nums[0];
        while (slow != slow2) {
            slow = nums[slow];
            slow2 = nums[slow2];
        }
        return slow;
    }
}

Complexity

Time: O(n) — treating values as indices forms a cycle, and Floyd's algorithm finds its start in linear time. Space: O(1) — only pointer variables are used, no extra array or set.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.