Find the Duplicate Number - Fast and Slow Pointers Pattern

Find the Duplicate Number in Java using the Fast and Slow Pointers pattern: problem statement, approach, template, complexity, and interview tips.

Find the Duplicate Number

Problem Statement

Given n + 1 integers in the range [1, n], find the repeated number without modifying the array and using constant extra space.

Pattern: Fast and Slow Pointers

Advance two pointers at different speeds to detect cycles, find midpoints, or find repeated values without extra memory.

Use this pattern when you work with linked lists or sequences that may loop, or you need the middle of a list in one pass.

Approach

  1. Start both pointers at the head (or start value).
  2. Move slow one step and fast two steps each iteration.
  3. Interpret where they meet or where fast ends.

Pattern Template (Java)

ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
    slow = slow.next;
    fast = fast.next.next;
    // if (slow == fast) a cycle exists
}

Adapt this template to the exact rules of Find the Duplicate Number: decide what state you track, what condition moves the loop forward, and what the final answer is.

Complexity

O(n) time and O(1) space.

Interview Tips

  • Check both fast and fast.next for null to avoid a NullPointerException.
  • For cycle start, reset one pointer to the head after the first meeting.
  • Start with a brute-force idea, state its complexity, then explain how the Fast and Slow Pointers pattern improves it.
  • Walk through a small example and at least one edge case (empty input, a single element, duplicates).

Continue Learning

Parent: DSA Interview Learning Path | Previous: Happy Number | Next: Middle of the Linked List

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.