InterviewPrepKit

Home / Coding / Linked List

Find the Duplicate Number

medium Original ↗
Solving tips
  • The read-only + O(1)-space constraints are the whole problem; note that every value is a valid index, so treat i -> nums[i] as an implicit linked list.
  • A duplicate value means two indices point to the same node, creating a cycle whose entry IS the duplicate; use Floyd's tortoise-and-hare in O(n) time, O(1) space.
  • Phase 1 finds a meeting point inside the cycle; phase 2 (restart slow at index 0, advance both at speed 1) finds the entry, and both phase-1 pointers must start at index 0.
  • Don't return the phase-1 meeting point (it's not the entry); a binary-search-on-value-range alternative (count of x <= mid) is O(n log n), O(1) if you forget the graph view.

Problem

You are given an array nums of n + 1 integers, each in the range [1, n]. By pigeonhole, at least one value must appear more than once — and here exactly one value is repeated (possibly more than twice). Return that repeated value.

The twist: you must not modify the array, and you must use only O(1) extra space. (Sorting in place, or marking visited slots by negating entries, are both off the table.)

Examples

  • Input: nums = [1, 3, 4, 2, 2] → Output: 2 n = 4; the value 2 appears twice.
  • Input: nums = [3, 1, 3, 4, 2] → Output: 3 3 is the repeated value.
  • Input: nums = [3, 3, 3, 3, 3] → Output: 3 The duplicate may appear many times — still one answer.

Constraints

  • 1 <= n <= 10^5, nums.length == n + 1
  • 1 <= nums[i] <= n
  • Exactly one value is repeated (one or more extra times).
  • The array is read-only; only constant extra space allowed.

Think about it first

Hint 1 Without the read-only / O(1)-space rules this is trivial (sort, or a hash set). The rules are the problem. What structure do the values impose? Every entry is a valid index into the array.
Hint 2 Try counting instead of marking: for a candidate m, how many entries are ≤ m? If the count exceeds m, the duplicate lies in [1, m]. That's a binary search over values, not positions.
Hint 3 Treat i -> nums[i] as a linked list: start at index 0 and repeatedly jump to the index given by the current value. A duplicate value means two indices point at the same node — the walk enters a cycle whose entry point is the duplicate. Floyd's cycle detection finds it in O(n) time, O(1) space.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.