Created
November 1, 2017 22:19
-
-
Save AdrianFerreyra/3a0f4ec2cdd6129934e60dec070c9abb to your computer and use it in GitHub Desktop.
How to detect a common superview (IOS Developer Interview Question)
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 commonSuperviews(between lhs: UIView, and rhs: UIView) -> [UIView] { | |
func getSuperviews(for view: UIView) -> [UIView] { | |
guard let superview = view.superview else { | |
return [] | |
} | |
return [superview] + getSuperviews(for: superview) | |
} | |
return Array(Set(getSuperviews(for: lhs)).intersection(Set(getSuperviews(for: rhs)))) | |
} |
Space complexity is optimised to O(1)
func getCommonSuperviews(with firstView:UIView, and secondView: UIView) -> UIView? {
var currentView = firstView.superview
var otherView = secondView.superview
firstView.tag = -1 // -1 means this node is visited.
while currentView != nil {
firstView.superview?.tag = -1 // -1 means this node is visited.
currentView = currentView?.superview
}
if secondView.tag == -1 { return secondView }
while otherView != nil {
// if view is visited before then return view
guard otherView?.tag != -1 else { return otherView }
otherView = otherView?.superview
}
return nil
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To get the first (lowest) common super view: