Uber | Phone screen | Group anagrams

Question 1:
https://leetcode.com/problems/group-anagrams

My Answer:

func groupAnagrams(_ strs: [String]) -> [[String]] {
    var dict = [String: [String]]()
    for str in strs {
        let sortedString = String(str.sorted())
        if  dict[sortedString] == nil {
            dict[sortedString] = [str]
        } else {
            dict[sortedString]?.append(str)
        }
    }
    return Array(dict.values)
}

Question 2:
Find a view from a heiracrchy clone given the B in a hierarchy find the b from the clone.
image

As in the above image the "clone @" is clone of "original A". Given B find b from "Clone @"

if let view = findView(B, in: a) {
 print("Found view \(view.tag)")
 } else {
 print("No view found!")
 }

//solution
func findView(_ view: UIView, in cloneView: UIView) -> UIView? {
    var indices = [Int]() 
    var viewB = view
    while let parentOfB = viewB.parentView { //Get the parentview of B and iterate it until it reach no parents which is the root
        let bIndex = parentOfB.Views.indexOf(viewB)  // get index of the child view 
        indices.append(bIndex), //save it in array
        viewB = parentOfB 
    }
    let newView: UIView
    for indx in indices.reversed() { //iterate cloneview to find b. Reverse it as we are starting from parent view to child
        newView = (clonewView.views)[indx] 
        
    }
    return newView
}
Comments (4)