Skip to content

Instantly share code, notes, and snippets.

@AdrianFerreyra
Created November 1, 2017 22:19
Show Gist options
  • Save AdrianFerreyra/3a0f4ec2cdd6129934e60dec070c9abb to your computer and use it in GitHub Desktop.
Save AdrianFerreyra/3a0f4ec2cdd6129934e60dec070c9abb to your computer and use it in GitHub Desktop.
How to detect a common superview (IOS Developer Interview Question)
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))))
}
@hossamghareeb
Copy link

To get the first (lowest) common super view:

extension UIView {
    func commonSuperView(otherView: UIView) -> UIView? {
        var pathToRoot = [UIView]()
        var current: UIView? = self
        while current != nil {
            pathToRoot.append(current!)
            current = current?.superview
        }

        var other: UIView? = otherView /// Check otherView then it's superview, and so on.
        while other != nil {
            if pathToRoot.contains(other!) { return other }
            other = other?.superview
        }
        return nil
    }
}

@EAlsharkawy
Copy link

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