Skip to content

Instantly share code, notes, and snippets.

@knowsudhanshu
Created April 4, 2024 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save knowsudhanshu/cfd5343a97e88f41ca18bd87775befbf to your computer and use it in GitHub Desktop.
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.
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