oneby7

Stacks and Queues Matching and cancelling

198. Find the Celebrity

Medium

There are n people at a party, numbered from 0 to n - 1. You are given an n × n table knows. knows[a][b] is 1 if person a knows person b, and 0 if not. Knowing goes one way: a can know b while b does not know a.

A celebrity is a person whom everyone else knows and who knows nobody else. Return the celebrity's number, or -1 if there is no celebrity.

In the interview version of this problem, the table is hidden, and each look at it is a call to a function knows(a, b). So try to look at as few entries as you can.

Example 1

1011011011001100001001011

Input: knows = [[1, 0, 1, 1, 0], [1, 1, 0, 1, 1], [0, 0, 1, 1, 0], [0, 0, 0, 1, 0], [0, 1, 0, 1, 1]]

Output: 3

Explanation: Persons 0, 1, 2 and 4 all know person 3, so column 3 is all ones. Row 3 has its only 1 on the diagonal, so person 3 knows nobody else.

Example 2

110110011

Input: knows = [[1, 1, 0], [1, 1, 0], [0, 1, 1]]

Output: -1

Explanation: Persons 0 and 2 both know person 1, but person 1 knows person 0, so person 1 is not a celebrity. Nobody else is known by everyone.

Example 3

1

Input: knows = [[1]]

Output: 0

Explanation: Person 0 is alone. Nobody else is there to know them, and there is nobody else for them to know.

Check your understanding

Work out the answer for this input before you write any code.

knows = [[1, 1, 1, 1], [0, 1, 1, 0], [0, 0, 1, 0], [0, 1, 1, 1]]

Constraints

  • n == knows.length == knows[i].length
  • 1 ≤ n ≤ 1000
  • knows[i][j] is 0 or 1
  • knows[i][i] == 1: everyone knows themselves

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.