Amazon Live coding Interview 1 USA

Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2024-11-04Added By Anonymous
Source: Link

Company: Amazon
Role: unknown
Interview Stage: Phone Screen
Location: USA
Year: unknown

Original Post Content:

I was asked to find lowest common ancestor of a n-ary tree. I couldn't complete the code in the allotted 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 employees 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