LeetCode #287 Medium

Find the Duplicate Number

Find the Duplicate Number is LeetCode 287 (Medium). The array nums holds n + 1 integers, each between 1 and n. Exactly one value is repeated, possibly more than twice. Return that value.

  • You may not modify nums.
  • You may use only O(1) extra space.

Those two rules remove the usual tools: sorting changes the array, and a hash set takes O(n) memory. With n up to 10⁵, the follow-up asks for linear time as well.

Constraints
  • 1 <= n <= 10⁵
  • 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.
arraytwo-pointersfloyd
Open on LeetCode ↗
02

Intuition

Read each index as a node with one arrow: index i points to index nums[i]. Every value is between 1 and n, so every arrow lands inside the array.

  • Why a cycle appears: start at index 0 and keep following arrows. There are only n + 1 nodes, so the walk must eventually revisit one.
  • Why it is the duplicate: no value is 0, so nothing points back to index 0. The first node reached twice therefore has two arrows coming in, from two different indices holding the same value. That node's index is the duplicate.

So the task becomes: find where the cycle starts. Floyd's tortoise and hare does that with two pointers and no extra memory.

How to spot this pattern

When a repeated value must be found without changing the array and with O(1) memory, look at the shape of the input: length n + 1 and values in 1..n point to reading nums[i] as a next-pointer, which turns the array into a linked list with a cycle.

03

Approach

Try it first

Before reading on: follow i → nums[i] from index 0 on [1,3,4,2,2] and write down the indices you visit. Which index do you reach twice, and how is it related to the answer? Aim for O(n) time and O(1) space.

1

Start both pointers at index 0

Set slow = fast = 0. Index 0 is a safe start because no value is 0, so it is the head of the list and never part of the cycle.

2

Race until the pointers meet

Repeat slow = nums[slow] and fast = nums[nums[fast]] until they are equal. Inside the cycle the fast pointer gains one node per round, so it is bound to catch the slow one; the meeting node is somewhere on the cycle.

3

Send one pointer back to the start

Set slow = 0 and leave fast at the meeting node. The distance from index 0 to the cycle entry equals the distance from the meeting node forward to the entry, counted around the cycle.

4

Walk both one step at a time

Repeat slow = nums[slow] and fast = nums[fast] until they meet again. Because both are the same number of steps from the entry, they arrive there together. Return that index: it is the duplicate value.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def findDuplicate(self, nums):
▶3 slow = fast = 0
▶4 while True:
▶5 slow = nums[slow]
▶6 fast = nums[nums[fast]]
▶7 if slow == fast:
▶8 break
▶9 slow = 0
▶10 while slow != fast:
▶11 slow = nums[slow]
▶12 fast = nums[fast]
▶13 return slow
valueindex10314223240slow + fast1324slow and fast start at index 0
slow0
fast0
Each index points to the index its value names: index 0 holds 1, so 0 → 1. No value is 0, so nothing points back to index 0 and it is a safe start. Following the arrows from 0 gives a short tail (0 → 1 → 3) and then a loop (2 → 4 → 2).
valueindex103142232401slow3fast24round 1: slow → 1, fast → 1 → 3
slow1one arrow from 0
fast3two arrows: 0 → 1 → 3
Slow follows one arrow, 0 → 1. Fast follows two, 0 → 1 → 3. Once both are on the loop, fast closes the gap by one index per round, so a meeting is guaranteed.
valueindex1031422324013slow24fastround 2: slow → 3, fast → 2 → 4
slow3one arrow from 1
fast4two arrows: 3 → 2 → 4
Slow follows one arrow, 1 → 3. Fast follows two, 3 → 2 → 4. Once both are on the loop, fast closes the gap by one index per round, so a meeting is guaranteed.
valueindex10314223240132slow4fastround 3: slow → 2, fast → 2 → 4
slow2one arrow from 3
fast4two arrows: 4 → 2 → 4
Slow follows one arrow, 3 → 2. Fast follows two, 4 → 2 → 4. Once both are on the loop, fast closes the gap by one index per round, so a meeting is guaranteed.
valueindex103142232401324slow + fastround 4: both on index 4 → stop
slow4one arrow from 2
fast4two arrows: 4 → 2 → 4
Slow follows one arrow, 2 → 4. Fast follows two, 4 → 2 → 4. They are on the same index, so both are inside the loop. This meeting index is not the answer yet: it can be anywhere on the loop, not only where the loop begins.
valueindex10314223240slow1324fastslow back to index 0, fast stays on 4
slow0start again
fast4meeting index
Put slow back at index 0 and leave fast on index 4. The number of arrows from 0 to the loop's first index equals the number from 4 forward to it, going round the loop. So if both now move one arrow at a time, they reach the loop's first index together.
valueindex103142232401slow32fast4slow → 1, fast → 2
slow1one arrow from 0
fast2one arrow from 4
Both follow exactly one arrow now: slow 0 → 1, fast 4 → 2. They are not together yet, so take another step each.
valueindex1031422324013slow24fastslow → 3, fast → 4
slow3one arrow from 1
fast4one arrow from 2
Both follow exactly one arrow now: slow 1 → 3, fast 2 → 4. They are not together yet, so take another step each.
valueindex10314223240132slow + fast4both arrive at index 2
slow2one arrow from 3
fast2one arrow from 4
Both follow exactly one arrow now: slow 3 → 2, fast 4 → 2. They land on the same index, which is where the loop begins.
valueindex10314223240132slow + fast4return 2
answer2
Index 2 is where the loop begins, so two arrows run into it: from index 3 and index 4. Two arrows into one index means two positions hold the value 2, so 2 is the duplicate. The array was only read, never changed.
05

Binary search on the value

Search over the values 1 to n, not over positions. Without a duplicate at or below mid, at most mid numbers could be <= mid. So a count above mid puts the duplicate in [lo, mid], and otherwise it is in [mid + 1, hi].

▶1class Solution:
▶2 def findDuplicate(self, nums):
▶3 lo, hi = 1, len(nums) - 1
▶4 while lo < hi:
▶5 mid = (lo + hi) // 2
▶6 count = sum(1 for x in nums if x <= mid)
▶7 if count > mid:
▶8 hi = mid
▶9 else:
▶10 lo = mid + 1
▶11 return lo
06

Common pitfalls

Returning the first meeting point

✗ Wrong
if slow == fast:
    return slow
✓ Right
slow = 0
while slow != fast:
    slow = nums[slow]
    fast = nums[fast]
return slow

The pointers first meet somewhere on the cycle, not necessarily at its entry. On [1,3,4,2,2] they meet at index 4, but the duplicate is 2.

Keeping the double step in the second walk

✗ Wrong
while slow != fast:
    slow = nums[slow]
    fast = nums[nums[fast]]
✓ Right
while slow != fast:
    slow = nums[slow]
    fast = nums[fast]

The second walk works only because both pointers are the same distance from the entry and move at the same speed. On [1,3,4,2,2] the double step keeps fast circling the cycle at a different pace, and the pointers meet at index 4, so the code returns 4 instead of 2.

Marking visited values by flipping signs

✗ Wrong
for x in nums:
    if nums[abs(x)] < 0:
        return abs(x)
    nums[abs(x)] *= -1
✓ Right
slow = fast = 0  # then Floyd's two walks

It finds the duplicate in one pass and passes the online tests, but it writes to nums, which the problem forbids. On [1,3,4,2,2] the array comes back as [1,-3,-4,-2,-2], and an interviewer will usually check this first.

07

Edge cases

The value repeats many times, such as [2,2,2,2,2]

Index 0 points to 2 and index 2 points to itself, so the cycle is one node long. Both walks end at index 2 and the answer is 2.

Some indices are never visited, such as [3,1,3,4,2]

Index 1 points to itself and is not on the path from index 0. The walk from 0 still reaches the cycle 3 → 4 → 2 → 3 and returns 3.

08

Complexity

Time
O(n)
Space
O(1)
The race ends within about one lap of the cycle after slow enters it, and the second walk covers the tail once. Only two indices are stored.
09

Find the Duplicate Number FAQ

Why must a duplicate exist?

It is the pigeonhole principle: n + 1 numbers are placed into only n possible values, 1 to n, so at least two of them share a value.

Why does the second walk end exactly at the entry?

Say the tail has a nodes, the cycle has c nodes, and the pointers meet b steps past the entry. Slow walked a + b steps and fast walked twice that, so the extra a + b steps are whole laps: a + b is a multiple of c. Walking a more steps from the meeting point therefore lands on the entry, and so does walking a steps from index 0.

Is this the same as Linked List Cycle II?

Yes, apart from the input. LeetCode 142 hands you real nodes; here the next pointer of index i is nums[i], and the node index where the cycle starts is the answer.