PPractick

DSA interview question

The Celebrity Problem

Hard · Data structures · Topics: stack, graph

The problem

At a party of n people, a celebrity is someone everyone else knows but who knows no one else. You're given an n × n matrix where M[i][j] = 1 means person i knows person j, and each lookup is an expensive question ("does i know j?"). Find the celebrity's index, or −1. Checking every candidate fully is O(n²) questions. One question always eliminates somebody: if i knows j, i isn't the celebrity; if not, j isn't. A two-pointer sweep leaves one candidate after n − 1 questions, and a final O(n) check confirms or rejects it.

Example: [[0,1,0],[0,0,0],[0,1,0]] → 1.

Function signature

int findCelebrity(const vector<vector<int>>& M);  // -1 if there is no celebrity

Test cases

Input MOutputExplanation
[[0,1,0],[0,0,0],[0,1,0]]1Everyone knows 1; 1 knows nobody
[[0,1],[1,0]]-1They know each other
[[1,1,0],[0,1,0],[0,1,1]]1The diagonal (knowing yourself) is ignored
[[0,0,1,0],[0,0,1,0],[0,0,0,0],[0,0,1,0]]2
[[0,0,0],[0,0,0],[0,0,0]]-1Nobody is known by the others
[[0]]0A lone person qualifies

(Confirm: at most one celebrity can exist; the diagonal M[i][i] carries no information and is ignored.)

How interviewers phrase it

Clarifying questions to ask

  1. Is the diagonal meaningful? (No, ignore it.)
  2. Can there be more than one celebrity? (No: two celebrities would each have to know the other.)
  3. Is each knows() lookup expensive? (That's why O(n) questions matters.)

Follow-ups to expect

  1. "Why does one question eliminate someone?"
  2. "Why is the final check needed?"
  3. "What's the stack version?"
  4. "How many questions in total?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in