KatInterview

Reporting Chain Length Between Two Employees

Trees & GraphsAuto-graded · 14 test cases

Last updated

Find the number of links on the path between two people in a company tree given as pairs, which tests undirected graph modeling and BFS or lowest common ancestor reasoning.

Reporting Chain Length

A company's structure is described by a list of direct reporting links. Each link is a pair [a, b] of names, meaning the two people are joined by one direct reporting line. For the answer, the order inside a pair does not matter. Taken together, the links connect everyone in the company into one tree with no cycles.

Given two names, person_a and person_b, return the number of reporting lines on the path that connects them.

The two people do not need to be in the same chain of command. They may sit in different branches, so the path can climb up to a shared manager and then descend to the other person.

Rules

  • If person_a and person_b are the same person, return 0.
  • Otherwise, return the number of links on the unique path between the two people.
  • A direct manager and report are at distance 1. Two people with the same direct manager are at distance 2.
  • If the second person could not be reached from the first, return -1. Valid inputs never require this.

Function

Implement reporting_distance(links, person_a, person_b):

  • links: a list of [name, name] pairs of strings.
  • person_a, person_b: the two names to compare.
  • Returns an integer, the number of links on the path between them.

Constraints

  • The links form a single connected tree, so there are no cycles and everyone is reachable from everyone else.
  • Names are non-empty strings, and each name identifies exactly one person.
  • Both queried names appear in at least one link, unless they are the same name.
  • The number of links is at most about 10^5.

Examples

Example 1

Input: reporting_distance([['CEO', 'VP'], ['VP', 'Manager'], ['Manager', 'Employee']], 'CEO', 'Employee')

Output: 3

Example 2

Input: reporting_distance([['CEO', 'VP'], ['CEO', 'CFO'], ['VP', 'Engineer'], ['CFO', 'Analyst']], 'Engineer', 'Analyst')

Output: 4

Hints

Hint 1

The direction of a link does not matter for counting steps. Think about what structure lets you move both up and down the hierarchy.

Hint 2

Build an adjacency list where each pair adds a neighbor in both directions, then explore outward level by level from the first person.

Hint 3

Handle the case where both names are equal before doing anything else, and keep a visited set so you never walk back along the edge you just used.