#287
Medium
Two Pointers

Find the Duplicate Number

Find the duplicate number in an array of n + 1 integers.

ArrayTwo Pointers

Pattern fit

The array can be reinterpreted as a linked structure where value points to next index, making the duplicate the cycle entry and turning the problem into Floyd cycle detection.

Key observation

You are not searching values directly; you are detecting a cycle in an implicit graph.

Target complexity

O(n) / O(1)

How to break down the solution cleanly

1

The array can be reinterpreted as a linked structure where value points to next index, making the duplicate the cycle entry and turning the problem into Floyd cycle detection.

2

You are not searching values directly; you are detecting a cycle in an implicit graph.

3

Write down what each pointer means before you move them.

4

Use the current comparison to prove which side can be safely discarded.

Reference implementation

Python
# Generic pattern template
# Opposite-direction pointers on a sorted array
left, right = 0, len(nums) - 1
while left < right:
    if good(nums[left], nums[right]):
        return answer
    if should_move_left(nums[left], nums[right]):
        left += 1
    else:
        right -= 1

# Fast/slow pointers
slow = 0
for fast in range(len(nums)):
    if keep(nums[fast]):
        nums[slow] = nums[fast]
        slow += 1

Common pitfalls

warning

Thinking the two pointers move over indices in the normal array sense.

warning

Forgetting the second phase needed to find the cycle entry.

Common follow-ups

Why does the cycle entry equal the duplicate value?

What alternative counting or binary-search methods exist?

Continue with related problems

Build repeatable depth inside the Two Pointers cluster before moving on.

view_weekBack to the pattern page
LeetCode 287. Find the Duplicate Number Guide | Interview AiBox