From 7d6b5ea811c5637738f7a8be3c8c24c5be3aae9c Mon Sep 17 00:00:00 2001 From: shubhakari Date: Wed, 16 Apr 2025 12:11:01 -0700 Subject: [PATCH] Completed Graph-3 --- findTheCelebrity.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 findTheCelebrity.py diff --git a/findTheCelebrity.py b/findTheCelebrity.py new file mode 100644 index 0000000..ab62539 --- /dev/null +++ b/findTheCelebrity.py @@ -0,0 +1,26 @@ +# The knows API is already defined for you. +# Returns a boolean, indicating whether person a knows person b. +# def knows(a: int, b: int) -> bool: + +class Solution: + # TC : O(n) + # SC : O(1) + def findCelebrity(self, n: int) -> int: + + candidate = 0 + + for i in range(1, n): + # If the candidate knows person i, then switch candidate to i + if knows(candidate, i): + candidate = i + + # Verify candidate is indeed a celebrity + for i in range(n): + if candidate != i: + # Candidate should not know anyone, and everyone should know the candidate + if knows(candidate, i) or not knows(i, candidate): + # If the condition fails, return -1 because there is no celebrity + return -1 + + # If all checks pass, return the candidate as the celebrity + return candidate \ No newline at end of file