Find the Celebrity

Find the celebrity

Problem Description

Solution Explanation

Implementation

# The knows API is already defined for you.

# return a bool, whether a knows b

# def knows(a: int, b: int) -> bool:

  

class Solution:

    numberOfPeople = 0

    def findCelebrity(self, n: int) -> int:

        self.numberOfPeople = n

        celebrityCandidate = 0 # start with 0

        for i in range(n):

            if (knows(celebrityCandidate, i)): # if 0 knows someone else

                celebrityCandidate = i # switch to them

        if self.isCelebrity(celebrityCandidate):

            return celebrityCandidate # check to see if celeb

        return -1

    def isCelebrity(self,i: int) -> bool: # brute force approach per person

        for j in range(self.numberOfPeople):

            if (i==j):

                continue

            if (knows(i,j) or not knows(j,i)):

                return False

        return True
FUNCTION findCelebrity(n):
	Set numberOfPeople = n
	Set celebrityCandidate = 0
	FOR i IN RANGE(n):
		IF (knows(celebrityCandidate, i)):
			celebrityCandidate = i
		ENDIF
	ENDFOR
	IF isCelebrity(celebrityCandidate, numberOfPeople):
		RETURN celebrityCandidate
	ENDIF
	RETURN -1
ENDFUNCTION

FUNCTION isCelebrity(celebrityCandidate, numberOfPeople):
	FOR i IN RANGE(numberOfPeople):
		IF (i==celebrityCandidate):
			continue // skip checking self
		ENDIF
		IF (knows(i, celebrityCandidate) OR NOT knows(celebrityCandidate, i)):
		RETURN false
	ENDFOR
	RETURN TRUE
ENDFUNCTION