Skip to content

Commit b1dcb75

Browse files
Added new algorithm to solve the famous celebrity problem using stack
Problem Description : Find the celebrity in a party. A celebrity is a person who: - Is known by everyone else - Knows no one else Args: mat: n x n adjacency matrix where mat[i][j] == 1 if person i knows person j. Returns: Index of the celebrity if one exists, else -1.
1 parent a71618f commit b1dcb75

1 file changed

Lines changed: 61 additions & 0 deletions

File tree

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
from __future__ import annotations
2+
3+
# Example input (matrix where mat[i][j] == 1 if person i knows person j)
4+
mat = [
5+
[1, 1, 0],
6+
[0, 1, 0],
7+
[0, 1, 1],
8+
]
9+
10+
# Expected output for this input
11+
expect = 1 # person at index 1 is the celebrity
12+
13+
14+
def celebrity(mat: list[list[int]]) -> int:
15+
"""
16+
Function to find the celebrity in a party.
17+
18+
A celebrity is a person who is:
19+
- Known by everyone else
20+
- Knows no one else
21+
- At max there can be only one celebrity
22+
Args:
23+
mat: n x n matrix, where mat[i][j] == 1 if person i knows person j.
24+
25+
Returns:
26+
Index of the celebrity if one exists, else -1.
27+
28+
Example:
29+
>>> celebrity(mat) == expect
30+
True
31+
"""
32+
n = len(mat)
33+
st: list[int] = list(range(n)) # push everybody in the stack
34+
35+
# Find a potential celebrity
36+
while len(st) > 1:
37+
a = st.pop()
38+
b = st.pop()
39+
40+
if mat[a][b]:
41+
st.append(b) # a knows b so a can't be celebrity
42+
else:
43+
st.append(a) # a doesn't know b so b can't be celebrity
44+
45+
# Potential candidate
46+
c = st.pop()
47+
48+
# Verify candidate
49+
for i in range(n):
50+
if i == c:
51+
continue
52+
if mat[c][i] or not mat[i][c]:
53+
return -1
54+
return c
55+
56+
57+
if __name__ == "__main__":
58+
from doctest import testmod
59+
60+
testmod()
61+
print("Celebrity is:", celebrity(mat))

0 commit comments

Comments
 (0)