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?- A. 2
- B. 9
- C. 7
- 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
- Problem: Find all values appearing more than ⌊n/3⌋ times with the extended Boyer–Moore vote (two candidates), then verify. python def…
- Find the bug: Boyer–Moore majority vote is used WITHOUT the verification pass on an array that may have no majority. python def…
- A 'shuffle' swaps each position i with a position chosen uniformly from the WHOLE array (0..n−1), for i = 0..n−1. Why is this not a…
- What is the time complexity of this loop? python for i in range(1, n + 1): j = i while j <= n: work() # O(1) j += i
- Problem: Maximum product of a contiguous subarray (values may be negative or zero). python def maxprod(a): hi = lo = best = a[0] for x in…
- Problem: Taking a value v earns v points for EVERY copy of v, but then all copies of v − 1 and v + 1 are deleted. Maximise the points…