15% off all plans & roadmaps Use code

See plans

Find the Duplicate Number

Updated

TL;DR: The array holds n + 1 values in the range 1 to n, so one value repeats. Treat each index as a node pointing to nums[index], and Floyd's cycle detection finds the repeated value in O(n) time and O(1) space without changing the array.

Problem

You are given an array of integers nums that contains n + 1 integers. Every integer is in the range [1, n] inclusive.

Exactly one value is repeated in nums. Return that repeated value.

You must not modify the array nums, and you may use only constant extra space.

Example 1

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

Example 2

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

Example 3

Input: nums = [3,3,3,3,3]
Output: 3

Constraints

  • 1 <= n <= 10^5
  • nums.length == n + 1
  • 1 <= nums[i] <= n
  • Every integer appears once, except for exactly one integer that appears two or more times.

Constraints that matter

  • n up to 10^5 means an O(n^2) pair check does about 5 * 10^9 comparisons in the worst case, which is too slow for most judges.
  • The array must not be modified, so sorting in place and negative marking are both out.
  • Constant extra space rules out a hash set and a frequency array, which both take O(n) memory.
  • Every value lies in [1, n] and the array has n + 1 slots, so every value is a valid index. That is what lets you follow values as pointers without going out of bounds.
  • The duplicate may appear more than twice, as in [3,3,3,3,3]. Any method that assumes exactly two copies needs a second look.

View on LeetCode

Hints

Hint 1

The pattern is fast and slow pointers, also called cycle detection.

Hint 2

Compare every pair of positions.

Solution

Intuition

The pattern is fast and slow pointers, also called cycle detection. The hint is in the constraints: n + 1 values drawn from 1 to n, so every value is a legal index. That means you can treat the array as a linked list where the node at index i points to index nums[i].

Picture a row of one-way signs where each sign points to another sign's position. The array is the set of signs, and the repeated value is the sign that two different signs point to, which is where the loop starts.

Start at index 0. Nothing points back to 0, because values are at least 1. From 0 you keep jumping, and since there are only n + 1 nodes you must eventually revisit one. A revisit means a cycle.

Now ask what creates the cycle. A node is entered from two places only if two indices hold the same value. The pigeonhole principle forces that: n + 1 indices point into n possible targets, so at least two indices share a target. That shared target is the duplicate, and it is exactly where the path enters the cycle.

So the problem becomes the linked list question: find the node where a cycle begins. Floyd's algorithm answers it with two integers and no changes to the array. Two other approaches are worth knowing: the pair check that ignores all structure, and a binary search over values that uses counting instead of memory.

Watch the pattern animation

Worked example

Input: nums = [9, 8, 7, 6, 5, 4, 3, 2, 1, 9]
Output: 9
Explanation: Here n = 9 and the array has 10 entries. The values 1 through 8 each appear once, and 9 appears at index 0 and at index 9, so 9 is the repeated value.

Approach 1: Brute force

Compare every pair of positions. The first pair with equal values gives the answer. This respects both rules, since it never writes to the array and keeps only loop counters.

It ignores everything the constraints tell you, so it pays for it in time.

Steps

  1. Loop i from 0 to the last index.
  2. For each i, loop j from i + 1 to the last index.
  3. If nums[i] == nums[j], return nums[i].
  4. The problem guarantees a duplicate, so the loops always return before ending.

Dry run

On [9,8,7,6,5,4,3,2,1,9], take i = 0 with value 9. The inner loop checks j = 1 through j = 8 and finds 8, 7, 6, 5, 4, 3, 2, 1, none equal to 9. At j = 9 the value is 9, so the function returns 9.

This input is the lucky case, because the duplicate involves index 0. If the repeated pair sat in the middle, the loops would run through far more pairs first.

Complexity

TimeO(n^2)
SpaceO(1)

Let n + 1 be the array length. The two nested loops examine up to (n + 1) * n / 2 pairs, which is quadratic in n. Only the indices i and j are stored, so extra space is constant.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def findDuplicate(self, nums: List[int]) -> int:
        size = len(nums)
        for i in range(size):
            for j in range(i + 1, size):
                if nums[i] == nums[j]:
                    return nums[i]
        return -1

Approach 2: Binary search on values

What's slow in the pair check is that it compares positions, which repeats a lot of work. The insight that fixes it is to search over the value range 1 to n instead of over positions, and use counting to decide which half holds the duplicate.

Pick a midpoint mid and count how many entries are less than or equal to mid. If values 1 through mid each appeared at most once, the count could not exceed mid. A count above mid means the duplicate is in [1, mid]. Otherwise it is in [mid + 1, n].

This holds even when the duplicate appears many times, by the pigeonhole principle applied to each half.

Steps

  1. Set lo = 1 and hi = n, where n is the array length minus 1.
  2. While lo < hi, compute mid = (lo + hi) / 2.
  3. Count the entries with value at most mid by scanning the whole array.
  4. If the count is greater than mid, set hi = mid. Otherwise set lo = mid + 1.
  5. When the loop ends, lo equals hi and is the duplicate.

Dry run

For [9,8,7,6,5,4,3,2,1,9], n = 9, so lo = 1, hi = 9.

lohimidcount of values <= middecision
1955 (values 5,4,3,2,1)5 is not greater than 5, so lo = 6
6977 (values 7,6,5,4,3,2,1)7 is not greater than 7, so lo = 8
8988 (values 8 down to 1)8 is not greater than 8, so lo = 9

Now lo = hi = 9, so the answer is 9.

Complexity

TimeO(n log n)
SpaceO(1)

Let n be the upper bound of the value range, so the array has n + 1 entries. The search halves the range each round, so it runs about log2(n) rounds. Each round scans n + 1 entries to count, giving O(n log n) time. Only lo, hi, mid and a counter are stored.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def findDuplicate(self, nums: List[int]) -> int:
        lo, hi = 1, len(nums) - 1
        while lo < hi:
            mid = (lo + hi) // 2
            # how many entries fall in the value range [1, mid]
            count = sum(1 for x in nums if x <= mid)
            if count > mid:
                hi = mid
            else:
                lo = mid + 1
        return lo
Fast & Slow (Cycle Detection) pattern infographic for Find the Duplicate Number

Solution pattern

Fast & Slow (Cycle Detection)

Part of Two Pointers

Approach 3: Floyd's cycle detectionOptimalFast & Slow (Cycle Detection)

What's slow in the binary search is that every round rescans the whole array. The insight that fixes it is to stop counting and walk the array as a linked list, where index i points to nums[i]. The duplicate is the node where the walk enters its cycle.

Floyd's tortoise and hare finds that node in one linear pass. Phase 1 moves slow one step and fast two steps from index 0 until they meet. The meeting point is somewhere inside the cycle, not necessarily the entrance.

Phase 2 resets slow to index 0 and leaves fast at the meeting point. Both now move one step at a time. They meet at the cycle entrance, which is the duplicate.

Phase 2 works because of the distances. Let L be the steps from index 0 to the entrance, C the cycle length, and X the distance from the entrance to the meeting point. When they meet, slow has walked L + X and fast has walked twice that. Fast's extra distance is a whole number of laps, so L + X = k * C for some k. That gives L = k * C - X, which is the distance from the meeting point forward to the entrance, so two pointers moving at equal speed from index 0 and from the meeting point reach the entrance together.

Steps

  1. Set slow = 0 and fast = 0.
  2. Repeat: slow = nums[slow], fast = nums[nums[fast]], until slow == fast.
  3. Reset slow = 0. Leave fast where it is.
  4. While slow != fast, set slow = nums[slow] and fast = nums[fast].
  5. Return slow.

Dry run

Array [9,8,7,6,5,4,3,2,1,9] has nums[0] = 9 and nums[9] = 9. The walk from 0 goes 0, 9, 9, 9 and so on, so the cycle is the single node 9.

StepPhaseslowfastNote
11nums[0] = 9nums[nums[0]] = nums[9] = 9equal, stop phase 1
2reset09slow goes back to index 0
32nums[0] = 9nums[9] = 9equal, stop
4return99answer is 9

A longer cycle shows both phases doing work. On [1,3,4,2,2], phase 1 gives slow/fast of 1/3, 3/4, 2/4, then 4/4. Phase 2 starts slow at 0 and fast at 4: they move to 1/2, then 3/4, then 2/2. The answer is 2.

Complexity

TimeO(n)
SpaceO(1)

Let n + 1 be the array length. The walk from index 0 visits at most n + 1 distinct nodes before repeating, so the tail length L and cycle length C satisfy L + C <= n + 1. Phase 1 ends within about L + C slow steps, since slow reaches the entrance after L steps and fast closes the gap inside the cycle in at most C more. Phase 2 takes exactly L steps.

The total is a small multiple of n, and the only storage is two integers.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def findDuplicate(self, nums: List[int]) -> int:
        slow = 0
        fast = 0
        # Phase 1: find a meeting point inside the cycle
        while True:
            slow = nums[slow]
            fast = nums[nums[fast]]
            if slow == fast:
                break
        # Phase 2: walk from the start and from the meeting point at equal speed
        slow = 0
        while slow != fast:
            slow = nums[slow]
            fast = nums[fast]
        return slow

Common mistakes

  • Returning slow right after phase 1. The meeting point is a node inside the cycle, not always the entrance. Run phase 2 with slow reset to 0 and return where the pointers meet.
  • Moving both pointers at the same speed in phase 1, such as fast = nums[fast]. They then never separate and the loop only ends by coincidence. Use fast = nums[nums[fast]].
  • Resetting slow to nums[0] in phase 2 while phase 1 started at 0. Both phases must start from the same head. Reset slow = 0 if phase 1 began at 0.
  • Sorting the array and comparing neighbours, or marking visited cells with negatives. Both write to nums, which the problem forbids. Floyd and the value binary search leave the array untouched.
  • Binary searching over indices instead of values, as in hi = len(nums). The search range is the value range 1 to n. Use hi = len(nums) - 1.
  • Using count >= mid or count < mid in the value search. The test that works is count > mid for the lower half. Anything weaker moves lo and hi to the wrong side and can skip the duplicate.

Edge cases

  • [1,1]: n = 1 and the only value is 1. All three methods return 1.
  • [3,3,3,3,3]: the duplicate appears five times. Floyd walks 0, 3, 3 and meets at 3. The binary search counts 5 entries at most 2, then at most 3... and still converges to 3.
  • [2,1,2]: the duplicate sits at both the middle value and the last index. Floyd walks 0, 2, 2 and returns 2.
  • [1,3,4,2,2]: the cycle has length 2 (2 then 4 then 2). Phase 2 is needed because phase 1 meets at 4, not 2.
  • Maximum size, n = 100000: the pair check does about 5 * 10^9 comparisons and times out. Floyd does a few hundred thousand steps.
  • Duplicate at the start, such as [9,8,7,6,5,4,3,2,1,9]: the cycle is a single self-loop at 9, and phase 1 ends after one step.

Follow-ups interviewers ask

How can you prove a duplicate must exist?
The array has n + 1 entries and each holds one of only n possible values. By the pigeonhole principle, two entries share a value. In the graph view, n + 1 nodes each have one outgoing edge into n targets, so some target has two incoming edges.
Can you solve it in linear time?
Yes, with Floyd's cycle detection. Phase 1 takes at most about L + C steps and phase 2 takes L steps, where L + C is at most n + 1. Memory is two integers and the array is never written.
What if you were allowed to modify the array or use extra space?
A hash set gives O(n) time and O(n) space. Sorting a copy and checking neighbours gives O(n log n) time. If writes are allowed, you can place each value at its own index by swapping and report the first collision, or flip signs at nums[x], both in O(n) time and O(1) extra space.

Find the Duplicate Number FAQ

What is the time complexity of Find the Duplicate Number?

The best solution, Floyd's cycle detection, runs in O(n) time and O(1) space. The binary search on values takes O(n log n) time, and the pair check takes O(n^2). Here n is the upper bound of the values, so the array has n + 1 entries.

Why use Floyd's cycle detection for Find the Duplicate Number?

Every value is a valid index, so the array is a linked list where index i points to nums[i]. A duplicate means two nodes point to the same target, which creates a cycle that starts at the duplicate. Floyd finds the start of a cycle in linear time with two pointers and no extra memory.

Can Find the Duplicate Number be solved in O(1) extra space?

Yes. Floyd's cycle detection and the binary search on values both use constant extra space and leave the array unchanged. A hash set does not qualify, since it grows with the input.

Why can you not sort the array in LeetCode 287?

Sorting in place modifies nums, which the problem forbids. Sorting a copy needs O(n) extra space, which breaks the constant space rule. Sorting also costs O(n log n), so it is slower than Floyd even where it is allowed.

Why does the second phase of Floyd's algorithm return the duplicate?

At the meeting point, the distance from index 0 to the cycle entrance equals the distance from the meeting point forward to the entrance, up to whole laps. Moving one pointer from each place at the same speed makes them arrive at the entrance together. The entrance is the value with two incoming edges, which is the duplicate.

How does the binary search solution for Find the Duplicate Number work?

It searches the value range 1 to n, not the positions. For a midpoint mid, it counts entries with value at most mid. If the count exceeds mid, the duplicate is in the lower half, otherwise in the upper half. It needs no memory beyond a few integers but rescans the array each round, so it is O(n log n).

Asked at

See which companies ask this — Pro

Practise it