Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: An array of n + 1 integers holds values 1..n with exactly one value repeated (possibly several times). Find it in O(1) extra space without modifying the array (Floyd's cycle detection on i → a[i]).

Problem: An array of n + 1 integers holds values 1..n with exactly one value repeated (possibly several times). Find it in O(1) extra space without modifying the array (Floyd's cycle detection on i → a[i]).
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, fast = a[slow], a[fast]
    return slow
print(dup([2, 5, 9, 6, 9, 3, 8, 9, 7, 1]))
What is printed?
  1. A. 2
  2. B. 9
  3. C. 7
  4. D. 6

Correct answer: B. 9

Treat index → a[index] as a linked list; the repeated value has two incoming pointers, so it is the entrance of the cycle. Phase 2 (one pointer restarted from the start) meets exactly there: 9. Sorting or a hash set would break the constraints.

More Coding Interview Problems questions

Exams that ask this topic