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

Problem: Find the celebrity (known by all, knows nobody) with O(n) calls to knows(a, b).

Problem: Find the celebrity (known by all, knows nobody) with O(n) calls to knows(a, b).
M = [[0, 1, 1, 0], [0, 0, 1, 0], [0, 0, 0, 0], [1, 1, 1, 0]]
calls = 0
def knows(a, b):
    global calls; calls += 1; return M[a][b] == 1
def celeb(n):
    c = 0
    for i in range(1, n):
        if knows(c, i): c = i
    for i in range(n):
        if i != c and (knows(c, i) or not knows(i, c)): return -1
    return c
print(celeb(4), calls)
What is printed?
  1. A. 2 3
  2. B. 3 9
  3. C. 2 12
  4. D. 2 9

Correct answer: D. 2 9

Elimination: if c knows i, c is not the celebrity, so i becomes the candidate; otherwise i is not. That takes n − 1 = 3 calls and leaves candidate 2. Verification needs up to 2 calls per other person (short-circuiting stops early only on failure): 3 × 2 = 6. Total 9 calls, O(n) instead of n².

More Coding Interview Problems questions

Exams that ask this topic