Lowest Common Manager

#!/bin/python3

class OrgChart:

    def __init__(self, name, manager):
        self.name = name
        self.manager = manager
        self.directReports = []

    def __repr__(self):
        return f'{self.name}'


def getLowestCommonManager(topManager, reportOne, reportTwo):
    report_one_manager = reportOne.manager
    report_one_chain = list()
    while report_one_manager:
        report_one_chain.append(report_one_manager)
        report_one_manager = report_one_manager.manager

    report_two_manager = reportTwo.manager
    report_two_chain = list()
    while report_two_manager:
        report_two_chain.append(report_two_manager)
        report_two_manager = report_two_manager.manager

    report_one_chain.reverse()
    report_two_chain.reverse()
    common_manager = None
    for a, b in zip(report_one_chain, report_two_chain):
        if a == b:
            common_manager = a
        else:
            break

    return common_manager


if __name__ == '__main__':
    org = [
        {"directReports": ["B", "C"], "id": "A", "name": "A"},
        {"directReports": ["D", "E"], "id": "B", "name": "B"},
        {"directReports": ["F", "G"], "id": "C", "name": "C"},
        {"directReports": ["H", "I"], "id": "D", "name": "D"},
        {"directReports": [], "id": "E", "name": "E"},
        {"directReports": [], "id": "F", "name": "F"},
        {"directReports": [], "id": "G", "name": "G"},
        {"directReports": [], "id": "H", "name": "H"},
        {"directReports": [], "id": "I", "name": "I"}
    ]

    top_manager = None
    members = {}
    for member in org:
        name = member['name']
        if name not in members:
            member_obj = OrgChart(name, None)
            top_manager = member_obj
            members[name] = member_obj

        member_obj = members[name]

        for direct_report in member['directReports']:

            if not direct_report in members:
                direct_report_obj = OrgChart(direct_report, member_obj)
                direct_report_obj.name = direct_report
                members[direct_report] = direct_report_obj
            else:
                direct_report_obj = members[direct_report]

            member_obj.directReports.append(direct_report_obj)

    print(getLowestCommonManager(top_manager, members['F'], members['H']))

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s