Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Given an array where values lie in 1..n, find the value that appears twice (exactly one does) without modifying the array.

Problem: Given an array where values lie in 1..n, find the value that appears twice (exactly one does) without modifying the array.
def dup(a):
    slow = fast = a[0]
    while True:
        slow = a[slow]
        fast = a[a[fast]]
        if slow == fast:
            break
    slow = a[0]
    while slow != fast:
        slow = a[slow]
        fast = a[fast]
    return slow
print(dup([3, 1, 3, 4, 2]))
What is printed?
  1. A. 1
  2. B. 3
  3. C. 4
  4. D. 2

Correct answer: B. 3

Treat i → a[i] as a linked list; the duplicate value is the entry point of the cycle, found by Floyd's slow/fast pointers. From index 0 the chain 0→3→4→2→3 loops at 3. O(n) time, O(1) space, array untouched (sorting or marking negatives would modify it).

More Coding Interview Problems questions

Exams that ask this topic