Find the Duplicate Number

MediumLinked Listfast and slow pointers

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an array nums of length n + 1 whose values all lie in the range [1, n]. By the pigeonhole principle at least one value repeats; in this problem **exactly one** value repeats, though it may appear more than twice. Return the repeated value. Do it without modifying nums and using only O(1) extra space. Aim for better than O(n^2) time.

Examples

Input: nums = [1,3,4,2,2]
Output: 2
2 appears twice.
Input: nums = [3,1,3,4,2]
Output: 3
3 appears twice.
Input: nums = [3,3,3,3,3]
Output: 3
The single repeated value can appear many times.

Constraints

  • 1 <= n <= 10^5
  • nums.length == n + 1
  • 1 <= nums[i] <= n
  • Exactly one value in `nums` appears two or more times

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More fast and slow pointers problems