The Celebrity Profile | Stack and Queue
An in-depth exploration of The Celebrity Problem, covering naive frequency-tracking array solutions, the combinatorial proof for maximum celebrity constraints, and the optimal linear-time two-pointer elimination algorithm.
1. Problem Statement & Definition
Imagine you are at a party with people, indexed from to . The relationships between the people are given as an binary matrix, denoted as matrix.
- Matrix Representation:
matrix[i][j] == 1means that personiknows personj. Conversely,matrix[i][j] == 0means personidoes not know personj. - The Definition of a Celebrity: A celebrity is a special individual at the party who satisfies two strict conditions:
- Known by Everyone: Every other person at the party knows the celebrity ( people know him/her).
- Knows No One: The celebrity does not know a single person at the party ( people are known by him/her).
Your goal is to identify and return the index of the celebrity. If no such person exists at the party, return -1.
Real-Life Analogy
Real-Life Analogy (The Famous VIP in a Room): Think of a room full of people where one person is an ultra-famous celebrity. Everyone in the room recognizes this celebrity (they wave or say hello to them), but the celebrity is so detached or reclusive that they recognize absolutely no one else in the room. Your job is to find this VIP using the fewest possible questions ("Do you know X?").
2. Understanding the Matrix & Diagonal Properties
Before diving into algorithmic solutions, it is vital to understand the structure of the input matrix.
People: 0, 1, 2, 3 (N = 4)
Person 0 Person 1 Person 2 Person 3
Person 0 [ 0 1 1 0 ]
Person 1 [ 0 0 0 0 ]
Person 2 [ 0 1 0 0 ]
Person 3 [ 0 1 1 0 ]
- Diagonal Elements (
matrix[i][i]): The entire main diagonal of the matrix contains0. This is because a person cannot know themselves (matrix[i][i]is always0). - Asymmetry: If
matrix[0][2] == 1(Person 0 knows Person 2), it does not imply thatmatrix[2][0] == 1. In our matrix above,matrix[2][0] == 0, meaning Person 2 does not know Person 0.
3. The Naive Approach: Frequency Tracking Arrays
The Core Idea
To determine if a person is a celebrity, we can count two distinct metrics for every single person:
- How many people know me? (
knowMecount) - How many people do I know? (
iKnowcount)
If a person is a true celebrity, their statistics will match these exact thresholds:
knowMe[i] == N - 1(Everyone knows them)iKnow[i] == 0(They know no one)
Naive Algorithm Walkthrough
- Create two frequency arrays of size , initialized to
0:knowMeandiKnow. - Iterate through every cell
(i, j)in the matrix. - If
matrix[i][j] == 1, it means personiknows personj. Therefore:- Increment
iKnow[i](Personiknows someone). - Increment
knowMe[j](Personjis known by someone).
- Increment
- After populating the arrays, iterate through all persons from
0toN - 1and check if any person satisfiesknowMe[i] == N - 1andiKnow[i] == 0.
Java Implementation (Naive Approach)
public class CelebrityProblemNaive {
public int findCelebrity(int[][] matrix) {
int n = matrix.length;
int[] knowMe = new int[n];
int[] iKnow = new int[n];
// Step 1: Populate frequency arrays by traversing the matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 1) {
iKnow[i]++;
knowMe[j]++;
}
}
}
// Step 2: Evaluate conditions for each person
for (int i = 0; i < n; i++) {
if (knowMe[i] == n - 1 && iKnow[i] == 0) {
return i; // Found the celebrity
}
}
return -1; // No celebrity found
}
}
Complexity Analysis of Naive Approach
- Time Complexity: because we must traverse every element in the matrix, plus an additional scan to check the arrays.
- Space Complexity: auxiliary space required for the
knowMeandiKnowarrays.
4. Why We Need Optimization & Bounding Maximum Celebrities
While the naive approach works, interviewers will ask for an optimization because it consumes extra space () and scans every single relationship regardless of logical eliminations.
Mathematical Proof: How Many Celebrities Can Exist?
- Minimum Celebrities: . If everyone knows everyone, or if relationships form cyclical loops where everyone knows someone else, no celebrity can exist.
- Maximum Celebrities: . You can never have two or more celebrities.
Proof by Contradiction:
Assume there are two distinct celebrities, X and Y.
- By definition, a celebrity must know no one. Therefore,
Xcannot knowY, andYcannot knowX. - Also by definition, everyone must know a celebrity. Therefore,
Xmust knowY(sinceYis a celebrity), andYmust knowX(sinceXis a celebrity). - This creates a direct contradiction:
Xboth knows and does not knowY. Thus, at most one celebrity can exist in any party of people.
5. The Optimal Approach: Two-Pointer Elimination
The Core Mental Model
Instead of checking every relationship in an grid, we can maintain two pointers:
top = 0(starting at the first person)down = N - 1(starting at the last person)
We systematically eliminate one person at a time by comparing top and down until top meets down.
Elimination Logic Rules
When comparing person top and person down:
- If
topknowsdown(matrix[top][down] == 1):topknows someone, sotopcannot be a celebrity (celebrities know no one). We incrementtop(top++).
- If
downknowstop(matrix[down][top] == 1):downknows someone, sodowncannot be a celebrity. We decrementdown(down--).
- If neither knows each other (
matrix[top][down] == 0andmatrix[down][top] == 0):- Neither can be the celebrity because a celebrity must be known by everyone (including the other person). We can eliminate both (
top++anddown--).
- Neither can be the celebrity because a celebrity must be known by everyone (including the other person). We can eliminate both (
6. Step-by-Step Flow Walkthrough
Let's trace the optimal elimination algorithm using our 4-person matrix:
Verification Phase
Because elimination only narrows down a candidate, we are not 100% sure person 1 is a celebrity yet. We must run a final validation scan on candidate 1:
- Check row
1: All elements must be0(knows no one). - Check column
1: All elements except the diagonal (matrix[1][1]) must be1(known by everyone).
If the candidate passes both checks, return 1. Otherwise, return -1.
7. Complete Optimized Java Implementation
public class CelebrityProblemOptimized {
public int findCelebrity(int[][] matrix) {
int n = matrix.length;
int top = 0;
int down = n - 1;
// Step 1: Eliminate non-celebrities using two pointers
while (top < down) {
if (matrix[top][down] == 1) {
// Top knows down -> Top cannot be celebrity
top++;
} else if (matrix[down][top] == 1) {
// Down knows top -> Down cannot be celebrity
down--;
} else {
// Neither knows each other -> Both cannot be celebrities
top++;
down--;
}
}
// If pointers crossed without finding a candidate
if (top > down) return -1;
int candidate = top;
// Step 2: Verify the single remaining candidate
for (int i = 0; i < n; i++) {
if (i == candidate) continue; // Skip diagonal
// Celebrity must NOT know 'i', and 'i' MUST know celebrity
if (matrix[candidate][i] == 1 || matrix[i][candidate] == 0) {
return -1;
}
}
return candidate;
}
}
8. Complexity Analysis
Summary and Key Takeaways
- Celebrity Definition: A celebrity is known by all ( people) and knows no one ( people).
- Upper Bound Constraint: There can be at most one celebrity at any party due to logical contradiction in mutual recognition rules.
- Diagonal Rule: Self-recognition (
matrix[i][i]) is always0and must be skipped during verification checks. - Two-Pointer Strategy: By utilizing a
topanddownpointer, we can eliminate impossible candidates in linear time without needing auxiliary arrays. - Verification is Mandatory: Elimination narrows the candidate pool down to a single suspect, but a full row/column scan is strictly required to confirm celebrity status and prevent false positives.