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?- A. 2 3
- B. 3 9
- C. 2 12
- 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
- Problem: Delete exactly one element from a binary array and return the longest run of 1s that can remain. python def afterdelete(a): l =…
- Problem: Find the minimum number of railway platforms with a sweep line over arrival and departure events (a train arriving when another…
- Problem: Find how many numbers in 1..n have all distinct digits — the digit-DP-free shortcut for n = 10ᵏ uses counting. python def…
- Problem: Find the minimum window length in which every one of k distinct product IDs appears at least once (k = number of distinct values…
- Problem: Find the number of operations to reduce n to 1: if even halve it, else add or subtract 1 (choose optimally). python def steps(n)…
- Problem: Find the minimum number of jumps for a knight to reach a target on an infinite board (BFS). python from collections import deque…