Locate a Celebrity Using an Acquaintance Matrix
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
At a gathering of n attendees labeled 0 through n - 1, you are given an n x n binary grid knows where knows[i][j] == 1 means attendee i recognizes attendee j, and knows[i][j] == 0 means attendee i does not recognize attendee j. Every diagonal entry knows[i][i] is 0.
An attendee c qualifies as the celebrity when both rules hold for every other attendee j != c:
- Every other attendee recognizes
c(knows[j][c] == 1). - Attendee
crecognizes no one else (knows[c][j] == 0).
Implement find_celebrity(knows: List[List[int]]) -> int to return the celebrity's index (0 to n - 1), or -1 when no attendee meets both rules. When n == 1, attendee 0 vacuously satisfies both conditions and the answer is 0.
Your implementation must inspect only O(n) grid cells rather than scanning all O(n^2) entries.
Examples
Example 1
Input: knows = [[0, 1, 1, 0],
[0, 0, 1, 1],
[0, 0, 0, 0],
[1, 0, 1, 0]]
Output: 2
Row 2 contains only 0s (attendee 2 recognizes nobody), while column 2 has 1 in rows 0, 1, and 3 (all other attendees recognize attendee 2).
Example 2
Input: knows = [[0, 1, 0],
[0, 0, 1],
[1, 0, 0]]
Output: -1
Attendee 0 recognizes 1, 1 recognizes 2, and 2 recognizes 0. Because every attendee recognizes at least one other person, no celebrity exists.
Example 3
Input: knows = [[0, 0, 0],
[1, 0, 0],
[1, 1, 0]]
Output: 0
Attendee 0 recognizes neither 1 nor 2, and both 1 and 2 recognize 0.
Constraints
1 <= n <= 2000, wheren == len(knows)and each row has lengthn.knows[i][j]is0or1for all0 <= i, j < n.knows[i][i] == 0for all0 <= i < n.- Target time complexity:
O(n)cell lookups withO(1)extra space.
Step-by-step walkthrough
Understand the celebrity rules and uniqueness
We are given an
n x nmatrixknowswhereknows[i][j] == 1means personiknows personj, and diagonal entriesknows[i][i]are always0.For person
cto be the celebrity, two conditions must hold for every other personj != c:knows[c][j] == 0—cknows nobody (rowcis all0s).knows[j][c] == 1— everyone else knowsc(columncis all1s exceptknows[c][c] == 0).
Example 1 (celebrity = 2): j=0 j=1 j=2 j=3 i=0 [ 0, 1, 1, 0 ] <- attendee 0 knows 2 i=1 [ 0, 0, 1, 1 ] <- attendee 1 knows 2 i=2 [ 0, 0, 0, 0 ] <- row 2 is all 0s (attendee 2 knows nobody) i=3 [ 1, 0, 1, 0 ] <- attendee 3 knows 2 ^^^ col 2 has 1s everywhere off the diagonalTwo quick sanity checks before we design the algorithm:
- Single person (
n = 1,[[0]]): There are no other peoplej != 0to violate either rule, so person0is trivially the celebrity (0). - At most one celebrity: Could two people
aandbboth be celebrities? No! Ifbis a celebrity, everyone (includinga) must knowb; yet ifais a celebrity,amust know nobody—a contradiction.
Why checking every person one by one is O(n^2)
A direct brute-force loop tests each person
cfrom0ton - 1by scanning rowcand columnc. In the worst case, that inspects up to2n(n - 1)entries—roughly8million reads whenn = 2000(and calling helpers likesum(knows[c])or1 in knows[c]still scans allncells of every row under the hood!).Notice something surprising: even though the
n x nmatrix is already in memory, our code does not have to read alln^2cells. We can solve the entire problem by inspecting fewer than3ncells!Key idea: every single lookup eliminates one suspect
Suppose we pick any two distinct people
aandband inspect one cell:knows[a][b]. Look at what happens in both possible outcomes:Lookup knows[a][b] (where a != b): +-- if 1 (a knows b) --> a knows someone, so a CANNOT be the celebrity! (Eliminate a) +-- if 0 (a doesn't know b) --> not everyone knows b, so b CANNOT be the celebrity! (Eliminate b)Whether the cell holds
1or0, we eliminate one suspect with a singleO(1)lookup! Starting withnsuspects,n - 1comparisons eliminaten - 1people and leave at most one possible candidate.Pass 1: narrow `n` people down to one candidate
Start with
candidate = 0and steppersonfrom1throughn - 1:- If
knows[candidate][person] == 1,candidateis disqualified andpersonbecomes our newcandidate. - Otherwise (
0),personis disqualified andcandidatestays unchanged.
Why can a real celebrity
cnever get skipped or eliminated here?- If
c == 0,knows[0][person]is0for everyperson, socandidatestays0the whole time. - If
c > 0, whoever holdscandidatewhenpersonreachescmust knowc(everyone knowsc!), soknows[candidate][c] == 1triggers andctakes over ascandidate. After that,knows[c][person] == 0for allperson > c, socnever loses the spot!
# Pass 1 (Elimination): narrow n suspects down to a single survivor in n - 1 lookups. # Invariant: after inspecting person k, nobody in {0 .. k} except `candidate` can be a celebrity. candidate = 0 for person in range(1, n): if knows[candidate][person] == 1: candidate = person- If
Pass 2: verify the survivor against both rules
Pass 1 guarantees that nobody other than
candidatecan be a celebrity—it does not guarantee that a celebrity exists at all! Two gaps remain unchecked for the finalcandidate:- Pass 1 never checked whether
candidateknows someone with an earlier index< candidate(for instance, in[[0, 1, 0], [0, 0, 1], [1, 0, 0]],candidatebecomes2, yetknows[2][0] == 1). - Pass 1 never checked whether everyone knows
candidate(in[[0, 0], [0, 0]],candidatestays0, yet nobody knows0).
So Pass 2 checks all
j != candidateinO(n)lookups. Remember to skipperson == candidate, becauseknows[c][c]is0by definition and would falsely triggerknows[person][candidate] == 0!# Pass 2 (Verification): Pass 1 only proves nobody ELSE can be the celebrity. # Confirm `candidate` knows nobody (including indices < candidate) and is known by everyone. for person in range(n): # Skip the diagonal: knows[c][c] is always 0 and would falsely fail the second check. if person == candidate: continue if knows[candidate][person] == 1: return -1 if knows[person][candidate] == 0: return -1 return candidateIf
candidatefails either check, we immediatelyreturn -1because all othern - 1people were already ruled out in Pass 1.- Pass 1 never checked whether
Trace through Examples 1 and 2
Example 1: knows = [[0, 1, 1, 0], [0, 0, 1, 1], [0, 0, 0, 0], [1, 0, 1, 0]] Pass 1: start: candidate = 0 person = 1: knows[0][1] == 1 -> eliminate 0, candidate = 1 person = 2: knows[1][2] == 1 -> eliminate 1, candidate = 2 person = 3: knows[2][3] == 0 -> eliminate 3, candidate = 2 (sole survivor) Pass 2 (verify candidate = 2): person = 0: knows[2][0] == 0 (ok) and knows[0][2] == 1 (ok) person = 1: knows[2][1] == 0 (ok) and knows[1][2] == 1 (ok) person = 2: skip diagonal person = 3: knows[2][3] == 0 (ok) and knows[3][2] == 1 (ok) Return 2 Example 2: knows = [[0, 1, 0], [0, 0, 1], [1, 0, 0]] Pass 1: start: candidate = 0 person = 1: knows[0][1] == 1 -> eliminate 0, candidate = 1 person = 2: knows[1][2] == 1 -> eliminate 1, candidate = 2 Pass 2 (verify candidate = 2): person = 0: knows[2][0] == 1 -> fails "knows nobody"! Return -1Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def find_celebrity(knows: List[List[int]]) -> int: n = len(knows) if n == 0: return -1 # Pass 1 (Elimination): narrow n suspects down to a single survivor in n - 1 lookups. # Invariant: after inspecting person k, nobody in {0 .. k} except `candidate` can be a celebrity. candidate = 0 for person in range(1, n): # If candidate knows `person`, candidate cannot be the celebrity (celebrities know nobody); # otherwise `person` is not known by candidate, so `person` cannot be the celebrity. if knows[candidate][person] == 1: candidate = person # Pass 2 (Verification): Pass 1 only proves nobody ELSE can be the celebrity. # Confirm `candidate` knows nobody (including indices < candidate) and is known by everyone. for person in range(n): # Skip the diagonal: knows[c][c] is always 0 and would falsely fail the second check. if person == candidate: continue if knows[candidate][person] == 1: return -1 if knows[person][candidate] == 0: return -1 return candidate✅ Submit now — all tests should pass.
Intuition & how it works
Think of the n people as nodes in a directed graph (a network of one-way arrows i -> j meaning "person i knows person j"), where a celebrity is a node with out-degree 0 (zero outgoing arrows—row c is all 0s) and in-degree n - 1 (incoming arrows from all n - 1 others—column c is all 1s off the diagonal). Instead of interviewing everyone about everyone else, run a knockout tournament: ask a single question, knows[a][b]? If the answer is 1, a knows someone so a is disqualified; if the answer is 0, b is unknown to a so b is disqualified. Every single question eliminates one suspect!
The naive approach computes row sums and column sums for each person, reading up to n^2 matrix entries (4,000,000 cells when n = 2,000) even though almost everyone can be ruled out with one glance. Conversely, running only the n - 1 knockout steps without checking the winner fails whenever no celebrity exists at all: a knockout bracket always leaves one person standing even in a room where nobody knows anybody! Combining n - 1 elimination steps with a 2(n - 1) verification scan solves both accuracy and speed in O(n) time.
Here is the two-pass trace on [[0, 1, 1, 0], [0, 0, 1, 1], [0, 0, 0, 0], [1, 0, 1, 0]]:
Pass 1 (Eliminate):
candidate = 0
vs person 1: knows[0][1] == 1 -> 0 is out, candidate = 1
vs person 2: knows[1][2] == 1 -> 1 is out, candidate = 2
vs person 3: knows[2][3] == 0 -> 3 is out, candidate = 2
Pass 2 (Verify candidate = 2):
person 0: knows[2][0] == 0 and knows[0][2] == 1 (pass)
person 1: knows[2][1] == 0 and knows[1][2] == 1 (pass)
person 3: knows[2][3] == 0 and knows[3][2] == 1 (pass) --> return 2
Complexity
Let n be the number of people (rows/columns of knows).
- Time:
O(n). Pass 1 inspects exactlyn - 1matrix cells, and Pass 2 inspects at most2(n - 1)cells alongcandidate's row and column, totaling at most3(n - 1)O(1)lookups without ever touching the remainingO(n^2)cells ofknows. - Space:
O(1)auxiliary space. Only two integer variables (candidateandperson) are allocated beyond the input matrix.
Edge cases
- Single person (
[[0]]): Pass 1 (range(1, 1)) and Pass 2 (person == candidate) do zero iterations and correctly return0. - Mutual acquaintances (
[[0, 1], [1, 0]]): Pass 1 leavescandidate = 1; Pass 2 catchesknows[1][0] == 1and returns-1. - Room of strangers (
n > 1, all0s): Pass 1 keepscandidate = 0; Pass 2 catchesknows[1][0] == 0and returns-1. - Everyone knows everyone (
1s everywhere off the diagonal): Pass 1 advancescandidateall the way ton - 1; Pass 2 catchesknows[n - 1][0] == 1and returns-1. - Celebrity at boundary index
0orn - 1: Index0starts ascandidateand is never replaced; indexn - 1replaces the previouscandidateon the very last step of Pass 1. - Survivor knows someone with a smaller index (
[[0, 0, 1], [0, 0, 1], [1, 0, 0]]): Pass 1 never queries row2, leavingcandidate = 2; Pass 2 checksknows[2][0] == 1and rejects2.
Common mistakes
- Skipping Pass 2 and returning
candidatedirectly. Pass 1 only proves that the othern - 1people are not celebrities; if no celebrity exists,candidateis a false positive. - Forgetting
if person == candidate: continuein Pass 2. Becauseknows[c][c]is always0, checkingknows[person][candidate] == 0onperson == candidatealways returns-1! - Only checking
person > candidate(or only checking one of the two rules) in Pass 2. Pass 1 never checkedknows[candidate][j]forj < candidate, norknows[j][candidate]for arbitraryj. - Using
sum(knows[i]) == 0inside a loop over alli. Eachsum(knows[i])scans allnelements of rowi, silently turning the algorithm back intoO(n^2)time.
Alternative approaches
- Two-pointer elimination: Start with
left = 0andright = n - 1; whileleft < right, advanceleft += 1ifknows[left][right] == 1elseright -= 1, then run the same Pass 2 check onleft. IdenticalO(n)time (<= 3(n - 1)lookups) andO(1)space. - Stack of candidates: Push
0 .. n - 1onto a stack, repeatedly pop two peoplea, b, and push back whichever oneknows[a][b]keeps alive. StillO(n)time, but wastesO(n)extra memory.
Follow-up questions
- Suppose you cannot index a matrix directly and instead can only call a helper query
has_met(a, b) -> bool—how would you adapt your solution and minimize calls? Replace everyknows[a][b] == 1lookup directly withhas_met(a, b)—because our algorithm never scans whole rows, it already works in at most3(n - 1)calls instead ofn(n - 1)! You can trim redundant queries in Pass 2 by observing that Pass 1 already verifiedhas_met(candidate, person) == Falsefor everyperson > candidate(andhas_met(prev_candidate, candidate) == Truefor the attendee who handedcandidatethe lead), dropping the worst-case call count from3n - 3to3n - 4forn >= 2. Ifhas_met(a, b)is a remote RPC, you can also run Pass 1 asO(log n)parallel knockout rounds (n - 1total queries) and fire all Pass 2 checks in one concurrent batch. - Why is it impossible for any deterministic algorithm to guarantee a correct answer in
o(n)queries? Consider an adversary argument (a lower-bound proof that answers each query consistently while keeping two valid inputs indistinguishable if too few queries are asked). Each off-diagonal lookupknows[a][b]eliminates at most one suspect (awhen1,bwhen0); if any attendeephas neither a1observed in rowpnor a0observed in columnp, all uninspected entries in rowpand columnpcould still makepa genuine celebrity. Ruling out everyone to return-1therefore requires at leastnlookups, and certifying attendeecrequires reading all2(n - 1)off-diagonal cells of rowcand columnc(flipping any unread cell would disqualifyc), establishing anOmega(n)lower bound. - Under the strict rules there can be at most one celebrity—what rule relaxation would allow multiple winners, and how would that affect the best possible runtime? When
n >= 2, two attendees cannot simultaneously satisfy both strict rules because one would have to recognize the other while also recognizing nobody. Multiple winners become possible only if we drop the outgoing rule and define a celebrity solely as anyone recognized by alln - 1others (in-degree == n - 1), regardless of whom they recognize. Once recognizing someone no longer eliminatesawhenknows[a][b] == 1, theO(n)knockout trick stops working: you must inspect each attendeec's column (breaking early on the first0), takingO(n^2)worst-case time—which is tight because on an off-diagonal all-1s grid every attendee qualifies and every single1must be checked.
Follow-up questions
- Suppose you cannot index a matrix directly and instead can only call a helper query `has_met(a, b) -> bool`—how would you adapt your solution and minimize calls?
- Why is it impossible for any deterministic algorithm to guarantee a correct answer in `o(n)` queries?
- Under the strict rules there can be at most one celebrity—what rule relaxation would allow multiple winners, and how would that affect the best possible runtime?
Similar questions
- Two-Thread Odd-Even Sequence Coordinator
- Palindrome Check on a Singly Linked List
- Maximum Contiguous Subarray Sum
- Collapse Adjacent Duplicate Letters
- System Architecture Walkthrough and Your Toughest Design Trade-Off
- Navigating Two High-Stakes Commitments on Colliding Timelines
More Omnissa interview questions
- Palindrome Check on a Singly Linked List Medium
- Maximum Contiguous Subarray Sum Medium
- System Architecture Walkthrough and Your Toughest Design Trade-Off Medium Pro
- Navigating Two High-Stakes Commitments on Colliding Timelines Medium Pro
- Two-Thread Odd-Even Sequence Coordinator Medium Pro
- Collapse Adjacent Duplicate Letters Medium Pro