Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Created April 11, 2024 01:39
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 JadenGeller/d48bdcc62d1a3c97a7029c08cf84853e to your computer and use it in GitHub Desktop.
Save JadenGeller/d48bdcc62d1a3c97a7029c08cf84853e to your computer and use it in GitHub Desktop.
func lowestCommonAncestor<ID: Hashable>(of ids: (ID, ID), parent: (ID) -> ID?) -> ID? {
var ancestor: (ID?, ID?) = ids
var visited: (Set, Set) = ([ids.0], [ids.1])
while ancestor.0 != nil || ancestor.1 != nil {
if let ancestor = ancestor.0 {
guard !visited.1.contains(ancestor) else { return ancestor }
}
if let ancestor = ancestor.1 {
guard !visited.0.contains(ancestor) else { return ancestor }
}
if let next = ancestor.0.flatMap(parent) {
ancestor.0 = next
visited.0.insert(next)
}
if let next = ancestor.1.flatMap(parent) {
ancestor.1 = next
visited.1.insert(next)
}
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment