Skip to the solution
EasyDSA15 min read

How do you find a duplicate in an array?

98 views

The problem

Question presented to candidate: "Given a list of integers, find a number that appears more than once. First solve it in general, then for the classic version โ€” n + 1 numbers, each between 1 and n, without modifying the list and with O(1) extra space. Please code it in Python."

What a strong answer should cover:

  • Asking about the constraints first: value range, whether the list may be modified, the memory budget, one or several repeated values.
  • The general answer: scan with a set, return the first value already in it โ€” O(n) time, O(n) space.
  • The alternatives: sort and compare neighbours (O(n log n)), index negation (O(n), O(1) space, modifies the list), and Floyd's cycle detection on i โ†’ nums[i] (O(n), O(1) space, read-only), with why the pigeonhole principle guarantees a duplicate.
  • Why Floyd works: two indices point to the duplicate, so it is the entrance of the cycle.
  • Python specifics: x in seen on a set is O(1) average but on a list is O(n); sorted() returns a copy while list.sort() mutates; len(set(nums)) != len(nums) for a yes/no; negative indices are valid in Python, so some index bugs are silent.

Clarifying questions expected:

  • What is the value range? May I modify the list? How much extra space?

Code / implementation expected: Yes โ€” a set-based find_duplicate in Python, plus the Floyd version for the 1..n constraint.

  • arrays
  • duplicates

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

15 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonHash set (any values) and Floyd cycle detection (values 1..n)
PythonFour approaches side by side, with a Floyd trace

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 36 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

How do you find the maximum depth of a binary tree?

Continue