Amazon Live coding Interview 1 USA

1173
Nov 04, 2024
Nov 04, 2024

I was asked to find lowest common ancestor of a n-ary tree. I couldn't complete the code in the alloted time but I was in the right track because I had solved the binary tree version. I used DFS with recursion.

Question: There are employee hierarchies in a company where empoloyees have manager(parent) and manager have reports(child). Given the root and two nodes find their lowest common ancestor.

Chatgpt code:

class Employee:
    def __init__(self, id):
        self.id = id
        self.reports = []

def find_lca(root, emp1, emp2):
    if not root:
        return None
    
    if root.id == emp1.id or root.id == emp2.id:
        return root
    
    lca_count = 0
    lca_node = None
    
    for report in root.reports:
        result = find_lca(report, emp1, emp2)
        if result:
            lca_count += 1
            if lca_count == 2:
                return root
            lca_node = result
    
    return lca_node

# Example usage
def build_hierarchy():
    ceo = Employee("CEO")
    vp1 = Employee("VP1")
    vp2 = Employee("VP2")
    manager1 = Employee("Manager1")
    manager2 = Employee("Manager2")
    employee1 = Employee("Employee1")
    employee2 = Employee("Employee2")
    
    ceo.reports = [vp1, vp2]
    vp1.reports = [manager1]
    vp2.reports = [manager2]
    manager1.reports = [employee1]
    manager2.reports = [employee2]
    
    return ceo

# Create the hierarchy
root = build_hierarchy()

# Find LCA
lca = find_lca(root, Employee("Employee1"), Employee("Employee2"))
print(f"The LCA is: {lca.id}")
Comments (2)