The Celebrity Problem: From Brute Force to O(n)
Imagine you walk into a party with a few hundred guests. You don't know who anyone is, but you're told that one person there might be a celebrity . You can only ask questions of the form: "Hey, do you know that person over there?" How many questions do you need to ask to find the celebrity, or to prove there isn't one? My first instinct when I met this problem was "just ask everyone about…
A celebrity is someone who satisfies two rules: everyone knows them, and they know nobody. You're given an n × n matrix M where M[i][j] = 1 means person i knows person j, and M[i][j] = 0 means person i does not know person j. Your task is to return the index of the celebrity, or -1 if there isn't one.
The brute force approach involves checking every person to see if they meet the celebrity criteria, resulting in a time complexity of O(n²) and constant space complexity. However, this can be slow for large values of n.
Instead, we can use a more efficient algorithm that eliminates people based on their relationships. We start by pushing all n people onto a stack. Then, we repeatedly pop two people, say a and b, and ask if a knows b. If a does know b, a can't be the celebrity (since a celebrity doesn't know anyone), so we push b back onto the stack.
If a doesn't know b, then b can't be the celebrity (since everyone knows a celebrity), so we push a back onto the stack. This process continues until only one person remains on the stack. Finally, we verify that the remaining person indeed satisfies the celebrity criteria by checking that everyone knows them and they know nobody, returning their index if so or -1 otherwise. This algorithm has a time complexity of O(n) and uses O(n) space for the stack.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.