150NeetCode 150

42.Find the Duplicate Number

MediumLinked List ยท 8/11

Problem

Given an array nums of n + 1 integers where every value is in the range [1, n], there is exactly one repeated number (it may appear two or more times). Return that number.

You must solve it without modifying nums and using only constant extra space.

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
Explanation: The duplicate can appear more than twice.

Constraints

  • 1 <= n <= 10^5
  • nums.length == n + 1
  • 1 <= nums[i] <= n
  • All the integers in nums appear only once except for precisely one integer, which appears two or more times.

๐Ÿ’ก Key Insight

Treat the array as a linked list: index i points to index nums[i]. Every value is a valid index in [1, n], and index 0 is never a target, so starting at 0 you walk into a structure that must loop. Two indices pointing to the same next index means the duplicate value is the entrance of the cycle โ€” exactly what Floyd's cycle detection finds in O(n) time and O(1) space, without touching the array.

Sorting

TimeO(n log n)SpaceO(n)

Intuition

After sorting, equal values sit next to each other, so the duplicate is the first i with nums[i] == nums[i - 1]. This breaks the "do not modify" rule (or costs O(n) to copy), but it is the natural first idea.

Algorithm

  1. Copy and sort nums.
  2. Return the first sorted[i] equal to sorted[i - 1].

Visualization

nums   = [3, 1, 3, 4, 2]
sorted = [1, 2, 3, 3, 4]
                 ^  ^   equal neighbours -> 3

Code

java
import java.util.Arrays;

class Solution {
    public int findDuplicate(int[] nums) {
        int[] sorted = nums.clone(); // avoid modifying the input
        Arrays.sort(sorted);
        for (int i = 1; i < sorted.length; i++) {
            if (sorted[i] == sorted[i - 1]) {
                return sorted[i];
            }
        }
        return -1; // unreachable for valid input
    }
}

Complexity

  • Time: O(n log n) โ€” sorting.
  • Space: O(n) โ€” the copy (O(log n) if you sorted in place, at the cost of modifying nums).

Complexity Comparison

Approach Time Space
Sorting O(n log n) O(n) (copy)
Hash Set O(n) O(n)
Binary Search on Values O(n log n) O(1)
Floyd's Cycle Detection O(n) O(1)

Common Pitfalls

  • Starting Phase 1 with slow == fast and a while (slow != fast) loop โ€” it exits immediately; use do-while or pre-advance the pointers.
  • Returning the Phase 1 meeting point โ€” it is somewhere in the cycle, not necessarily the entrance.
  • Starting the walk at an index other than 0; index 0 is guaranteed to be outside the cycle because no value equals 0.
  • Sorting in place or marking visited values with negation โ€” both modify nums, which the problem forbids.
  • In binary search, comparing count > mid with indices instead of values.