InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Linked List

Find the Duplicate Number

medium Original ↗ 00:00

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.

Two extra constraints apply: you must not modify the array, and you must use only O(1) extra space. This rules out sorting in place and marking visited slots by negating entries.

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 and O(1)-space rules this is trivial: sort the array, or use a hash set. Those two constraints are what make the problem hard. Consider the structure 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug