Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Josephus problem: n people in a circle, every k-th person is eliminated; find the 1-based position of the survivor.
Problem: Josephus problem: n people in a circle, every k-th person is eliminated; find the 1-based position of the survivor.
def josephus(n, k):
pos = 0
for m in range(2, n + 1):
pos = (pos + k) % m
return pos + 1
print(josephus(7, 3), josephus(10, 2))What is printed?- A. 7 5
- B. 4 9
- C. 3 5
- D. 4 5
Correct answer: D. 4 5
J(1) = 0 and J(m) = (J(m − 1) + k) mod m (0-based). For n = 7, k = 3 this gives position 4; for k = 2 the closed form 2(n − 2^⌊log₂ n⌋) + 1 = 2(10 − 8) + 1 = 5.
More Coding Interview Problems questions
- Problem: Count permutations of 1..n where, for every position i (1-based), the value is divisible by i or i is divisible by the value…
- Problem: Each candidate can be used at most ONCE and the list has duplicates; count the distinct combinations that sum to the target…
- Problem: Divide two integers without , / or %, truncating toward zero, using doubling (shifts). python def divide(a, b): neg = (a < 0) !=…
- Problem: Traverse a matrix along anti-diagonals, alternating direction (up-right first). python def diag(m): R, C = len(m), len(m[0]); out…
- Edge case: building a 3 × 3 grid with list multiplication. python grid = [[0] 3] 3 grid[0][0] = 1 print(grid) What is printed?
- Edge case: lambdas created in a loop (closures). python fs = [lambda: i 10 for i in range(3)] gs = [lambda i=i: i 10 for i in range(3)]…