Created
April 11, 2024 01:39
-
-
Save JadenGeller/d48bdcc62d1a3c97a7029c08cf84853e to your computer and use it in GitHub Desktop.
This file contains 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 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