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 c recognizes 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, where n == len(knows) and each row has length n.
  • knows[i][j] is 0 or 1 for all 0 <= i, j < n.
  • knows[i][i] == 0 for all 0 <= i < n.
  • Target time complexity: O(n) cell lookups with O(1) extra space.

Step-by-step walkthrough

  1. Understand the celebrity rules and uniqueness

    We are given an n x n matrix knows where knows[i][j] == 1 means person i knows person j, and diagonal entries knows[i][i] are always 0.

    For person c to be the celebrity, two conditions must hold for every other person j != c:

    1. knows[c][j] == 0 — c knows nobody (row c is all 0s).
    2. knows[j][c] == 1 — everyone else knows c (column c is all 1s except knows[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 diagonal
    

    Two quick sanity checks before we design the algorithm:

    • Single person (n = 1, [[0]]): There are no other people j != 0 to violate either rule, so person 0 is trivially the celebrity (0).
    • At most one celebrity: Could two people a and b both be celebrities? No! If b is a celebrity, everyone (including a) must know b; yet if a is a celebrity, a must know nobody—a contradiction.
  2. Why checking every person one by one is O(n^2)

    A direct brute-force loop tests each person c from 0 to n - 1 by scanning row c and column c. In the worst case, that inspects up to 2n(n - 1) entries—roughly 8 million reads when n = 2000 (and calling helpers like sum(knows[c]) or 1 in knows[c] still scans all n cells of every row under the hood!).

    Notice something surprising: even though the n x n matrix is already in memory, our code does not have to read all n^2 cells. We can solve the entire problem by inspecting fewer than 3n cells!

  3. Key idea: every single lookup eliminates one suspect

    Suppose we pick any two distinct people a and b and 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 1 or 0, we eliminate one suspect with a single O(1) lookup! Starting with n suspects, n - 1 comparisons eliminate n - 1 people and leave at most one possible candidate.

  4. Pass 1: narrow `n` people down to one candidate

    Start with candidate = 0 and step person from 1 through n - 1:

    • If knows[candidate][person] == 1, candidate is disqualified and person becomes our new candidate.
    • Otherwise (0), person is disqualified and candidate stays unchanged.

    Why can a real celebrity c never get skipped or eliminated here?

    • If c == 0, knows[0][person] is 0 for every person, so candidate stays 0 the whole time.
    • If c > 0, whoever holds candidate when person reaches c must know c (everyone knows c!), so knows[candidate][c] == 1 triggers and c takes over as candidate. After that, knows[c][person] == 0 for all person > c, so c never 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
    
  5. Pass 2: verify the survivor against both rules

    Pass 1 guarantees that nobody other than candidate can be a celebrity—it does not guarantee that a celebrity exists at all! Two gaps remain unchecked for the final candidate:

    1. Pass 1 never checked whether candidate knows someone with an earlier index < candidate (for instance, in [[0, 1, 0], [0, 0, 1], [1, 0, 0]], candidate becomes 2, yet knows[2][0] == 1).
    2. Pass 1 never checked whether everyone knows candidate (in [[0, 0], [0, 0]], candidate stays 0, yet nobody knows 0).

    So Pass 2 checks all j != candidate in O(n) lookups. Remember to skip person == candidate, because knows[c][c] is 0 by definition and would falsely trigger knows[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 candidate
    

    If candidate fails either check, we immediately return -1 because all other n - 1 people were already ruled out in Pass 1.

  6. 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 -1
    
  7. Complete 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 exactly n - 1 matrix cells, and Pass 2 inspects at most 2(n - 1) cells along candidate's row and column, totaling at most 3(n - 1) O(1) lookups without ever touching the remaining O(n^2) cells of knows.
  • Space: O(1) auxiliary space. Only two integer variables (candidate and person) 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 return 0.
  • Mutual acquaintances ([[0, 1], [1, 0]]): Pass 1 leaves candidate = 1; Pass 2 catches knows[1][0] == 1 and returns -1.
  • Room of strangers (n > 1, all 0s): Pass 1 keeps candidate = 0; Pass 2 catches knows[1][0] == 0 and returns -1.
  • Everyone knows everyone (1s everywhere off the diagonal): Pass 1 advances candidate all the way to n - 1; Pass 2 catches knows[n - 1][0] == 1 and returns -1.
  • Celebrity at boundary index 0 or n - 1: Index 0 starts as candidate and is never replaced; index n - 1 replaces the previous candidate on 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 row 2, leaving candidate = 2; Pass 2 checks knows[2][0] == 1 and rejects 2.

Common mistakes

  • Skipping Pass 2 and returning candidate directly. Pass 1 only proves that the other n - 1 people are not celebrities; if no celebrity exists, candidate is a false positive.
  • Forgetting if person == candidate: continue in Pass 2. Because knows[c][c] is always 0, checking knows[person][candidate] == 0 on person == candidate always returns -1!
  • Only checking person > candidate (or only checking one of the two rules) in Pass 2. Pass 1 never checked knows[candidate][j] for j < candidate, nor knows[j][candidate] for arbitrary j.
  • Using sum(knows[i]) == 0 inside a loop over all i. Each sum(knows[i]) scans all n elements of row i, silently turning the algorithm back into O(n^2) time.

Alternative approaches

  • Two-pointer elimination: Start with left = 0 and right = n - 1; while left < right, advance left += 1 if knows[left][right] == 1 else right -= 1, then run the same Pass 2 check on left. Identical O(n) time (<= 3(n - 1) lookups) and O(1) space.
  • Stack of candidates: Push 0 .. n - 1 onto a stack, repeatedly pop two people a, b, and push back whichever one knows[a][b] keeps alive. Still O(n) time, but wastes O(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 every knows[a][b] == 1 lookup directly with has_met(a, b)—because our algorithm never scans whole rows, it already works in at most 3(n - 1) calls instead of n(n - 1)! You can trim redundant queries in Pass 2 by observing that Pass 1 already verified has_met(candidate, person) == False for every person > candidate (and has_met(prev_candidate, candidate) == True for the attendee who handed candidate the lead), dropping the worst-case call count from 3n - 3 to 3n - 4 for n >= 2. If has_met(a, b) is a remote RPC, you can also run Pass 1 as O(log n) parallel knockout rounds (n - 1 total 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 lookup knows[a][b] eliminates at most one suspect (a when 1, b when 0); if any attendee p has neither a 1 observed in row p nor a 0 observed in column p, all uninspected entries in row p and column p could still make p a genuine celebrity. Ruling out everyone to return -1 therefore requires at least n lookups, and certifying attendee c requires reading all 2(n - 1) off-diagonal cells of row c and column c (flipping any unread cell would disqualify c), establishing an Omega(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 all n - 1 others (in-degree == n - 1), regardless of whom they recognize. Once recognizing someone no longer eliminates a when knows[a][b] == 1, the O(n) knockout trick stops working: you must inspect each attendee c's column (breaking early on the first 0), taking O(n^2) worst-case time—which is tight because on an off-diagonal all-1s grid every attendee qualifies and every single 1 must be checked.

Follow-up questions

Similar questions

More Omnissa interview questions

All 7 Omnissa questions →