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?- A. 1
- B. 3
- C. 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
- Problem: Given n ≤ 10⁵ integers (not sorted), find the length of the longest run of consecutive values, e.g. [100, 4, 200, 1, 3, 2] → 4…
- Problem: Group words that are anagrams of each other and report how many groups there are. python from collections import defaultdict def…
- Problem: Count the number of contiguous subarrays whose sum equals k. Values can be negative. python def countk(a, k): seen = {0: 1} p =…
- Problem: Count subarrays whose sum is divisible by k (values may be negative). python def divk(a, k): cnt = [0] k cnt[0] = 1 p = ans = 0…
- Problem: For n ≤ 2 × 10⁵ integers in the range −10⁴..10⁴, count subarrays with sum exactly k. Why does a two-pointer sliding window NOT…
- Problem: A game keeps scores in a non-decreasing array. Remove duplicates in place and return the number of unique scores. python def…