Q (MS 2018): write an algorithm to search for celebrities in a collection of people with the help of a blackbox predicate that can tell whether one person knows the other (bool a.knows(b)) which is an asymmetric relation. Celebrities are those who know no one but are known by everyone else.
Aha : There can be 0 or 1 celebrity.
There are exactly N*(N-1) relationships in the system, so brute force is O(N*N) but I propose a 2-pass O(N) solution:
- First pass: shrink the collection of Nodes [A, B .. N]
- check a random pair. if A knows B, then remove A from list; else, remove B from list. So first step always shrinks list by one
- Now check any random pair of persons in remaining list. Check either direction. Will remove exactly one person.
- list will shrink to 1 person (Dan) after N-1 steps
- Second pass: check this Dan thoroughly. Dan must be known to everyone and must not know anyone. We end up with either no celebrity OR one celebrity in Dan.
Aha — better use A/B/C or Alice/Bob/Cody instead of #1, #2, #3.