Algo-Sim › Linked Lists

Find the Duplicate Number

Medium · Linked Lists · step through it in Java, Python and C++ on your own input

Find the one repeated value in n + 1 numbers from 1..n without changing the array or using extra memory. Treat i → nums[i] as a linked list and find its cycle's entry with Floyd's pointers.

Problem

An array nums holds n + 1 integers, each between 1 and n, so some value must repeat. Exactly one value repeats, though it may appear more than twice. Return it without modifying nums, using only constant extra space.

Constraints

Edge cases to test

Follow-up questions

Why is it a linked list?
Treat i → nums[i] as a next pointer. Values are 1..n so 0 is never pointed to, and the duplicate value is where two pointers enter the cycle.
What else meets the O(1)-space, read-only rule?
Binary search on the value: count how many numbers are ≤ mid (pigeonhole): O(n log n).

Solution

Java

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

Python

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

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int findDuplicate(vector<int> &nums) {
        int slow = 0, fast = 0;
        do {
            slow = nums[slow];
            fast = nums[nums[fast]];
        } while (slow != fast);
        int entry = 0;
        while (entry != slow) {
            entry = nums[entry];
            slow = nums[slow];
        }
        return entry;
    }
};

More Linked Lists problems