Reporting Chain Length Between Two Employees
Trees & GraphsAuto-graded · 14 test casesLast 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_aandperson_bare the same person, return0. - 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 distance2. - 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.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The links form a tree, and the answer is the number of edges on the path between the two people. That path can go up to a shared manager and then down, so the direction of each link is irrelevant. Each pair becomes an undirected edge, and a breadth-first search from person_a finds the distance to person_b.
Steps:
- If both names are equal, return
0. - Build an adjacency list, adding each person to the other's neighbor list.
- Run BFS from
person_a, storing each node's distance from the start. Mark nodes as visited when they are enqueued so no edge is walked backward. - When a neighbor equals
person_b, return the current distance plus one. - If the queue empties without finding
person_b, return-1. This is only a safety fallback, since the input is guaranteed connected.
Why it is correct
BFS visits nodes in non-decreasing order of distance from the start, so the first time person_b is seen, the recorded distance is the shortest one. In a tree, the only simple path between two nodes goes through their lowest common manager, so the shortest path is exactly the reporting path. Checking for person_b when generating neighbors rather than when dequeuing returns one step earlier and gives the same value.
Complexity
With N people there are N - 1 links.
- Time:
O(N), to build the graph and to visit each node and edge at most once. - Space:
O(N), for the graph, the visited set and the queue.
An alternative is to store each person's parent, compute depths, and answer with depth(a) + depth(b) - 2 * depth(lca). This is also linear for one query and pays off with binary lifting when there are many queries. However, it needs the parent direction, so BFS is simpler here.
Reference solution
from collections import deque
from typing import List
def reporting_distance(links: List[List[str]], person_a: str, person_b: str) -> int:
if person_a == person_b:
return 0
# Undirected adjacency list: each link can be walked in both directions.
graph = {}
for first, second in links:
graph.setdefault(first, []).append(second)
graph.setdefault(second, []).append(first)
# Breadth-first search from person_a.
queue = deque([(person_a, 0)])
visited = {person_a}
while queue:
current, dist = queue.popleft()
for nxt in graph.get(current, []):
if nxt == person_b:
return dist + 1
if nxt not in visited:
visited.add(nxt)
queue.append((nxt, dist + 1))
return -1