← Questions

Find the duplicate number

0
CognitionCodingLast asked Oct 2024

A coding interview question asked in Cognition's coding screen, last asked Oct 2024. It tests arrays, binary-search and cycle detection.

A list holds n + 1 integers, each between 1 and n, so at least one value appears more than once. Return a value that repeats. You may not modify the list and may use only constant extra space, so sorting a copy and hash sets are ruled out.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • find_duplicate(nums: list[int]) -> int — when exactly one value repeats (possibly many times), return it.

Example

find_duplicate([1, 3, 4, 2, 2])  ->  2
find_duplicate([3, 1, 3, 4, 2])  ->  3
find_duplicate([2, 2, 2, 2, 2])  ->  2    # one value repeated several times

Constraints

  • 1 <= n <= 10^5; len(nums) == n + 1; 1 <= nums[i] <= n.
  • Read-only input, O(1) extra space, better than O(n^2) time.

Clarifying questions

  • Is exactly one value duplicated, or could several be, and is any one of them acceptable?
  • Can the duplicate appear more than twice?
  • Is the list truly read-only, or may it be modified and restored?

What a strong answer covers

  • Why the obvious answers fail the rules: a set is O(n) space, sorting modifies the input, the pairwise check is O(n^2).
  • Treat i -> nums[i] as a linked list. Index 0 is never a target, so following it must enter a cycle, and the cycle's entrance is the duplicate. Floyd's tortoise and hare finds it in O(n) time and O(1) space; explain why resetting one pointer to the start meets at the entrance.
  • The alternative: binary search on the value range, counting how many elements are <= mid (pigeonhole), O(n log n).
  • Edge cases: the duplicate repeated many times, n = 1, the duplicate at index 0.

Follow-ups

  • Prove the cycle-entrance step of Floyd's algorithm.
  • Return every value that repeats, still read-only (now with more space allowed, or modifying the list).
  • The numbers arrive as a stream that can be read only once.

Where it's asked

What it tests

arrays · binary-search · cycle detection

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding