Created
April 4, 2024 14:56
-
-
Save knowsudhanshu/cfd5343a97e88f41ca18bd87775befbf to your computer and use it in GitHub Desktop.
In a party of N people, only one person known to everyone but doesn't know anyone. Such a person is called celebrity.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func getCelebrity(input: [[Int]]) -> Int { | |
// Add person to stack | |
var stack: [Int] = [] | |
for i in 0..<input.count { | |
stack.append(i) | |
} | |
// pick a person and check with others | |
while stack.count > 1 { | |
let first = stack.removeLast() | |
let second = stack.removeLast() | |
if input[first][second] == 1 { | |
stack.append(second) | |
} else { | |
stack.append(first) | |
} | |
} | |
let celebrity = stack.removeLast() | |
var rowZero = true | |
// RowCheck | |
for i in 0..<input.count { | |
if input[celebrity][i] == 1 { | |
rowZero = false | |
} | |
} | |
var columnOne = true | |
for i in 0..<input.count { | |
if input[i][celebrity] == 0 && i != celebrity { | |
columnOne = false | |
} | |
} | |
if rowZero && columnOne { | |
return celebrity | |
} else { | |
return -1 | |
} | |
} | |
let input = [[0, 1, 1, 0], | |
[0, 0, 1, 0], | |
[0, 0, 0, 0], | |
[1, 0, 1, 0]] | |
print(getCelebrity(input: input)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment