Org Chart Inference with Manager and Peer Links
Data Structure DesignModel answerLast updated
Design a structure that records manager and same-manager links between employee IDs and answers whether one employee sits above another, including facts inferred from earlier updates.
Design an in-memory class that tracks reporting relationships among employees identified by ID. It must support three operations:
add_manager(a, b): record thatais the direct manager ofb.add_peer(a, b): record thataandbreport to the same direct manager. That manager may not be known yet.is_manager(a, b): returntrueifais a manager ofb, andfalseotherwise.
Answers must reflect everything that can be inferred from earlier calls. For example, after add_manager("m", "x") and add_peer("x", "y"), the call is_manager("m", "y") must return true, because y shares x's manager.
Assumptions:
- The recorded facts are logically consistent, and the org chart never contains a cycle.
- Calls can arrive in any order. A peer fact may be recorded before anyone knows who the manager is.
- Treat "manager of" as meaning any level above: if
mmanagesxandxmanagesy, thenis_manager(m, y)istrue. Mention how your design changes if only direct managers should count.
Describe your data structures, implement the three operations, and give time and space complexity. Also discuss the edge cases you would handle.
Hints
Hint 1
Ask which relation is an equivalence relation. 'Has the same direct manager as' is reflexive, symmetric and transitive, so it splits employees into disjoint groups that merge over time.
Hint 2
Store the manager once per peer group rather than once per person. If the group's representative holds the manager ID, every present and future member of the group gets it automatically.
Hint 3
When two groups merge, keep whichever manager is known. To answer a query, repeatedly jump from the person to their group's manager and compare with the candidate, stopping when no manager is known.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying questions
- Direct or transitive? I will implement "any level above", since that is the usual intent. The direct-only version is a one-line change, shown at the end.
- Can the manager be unknown? Yes.
add_peer(x, y)may come first, so the model must hold "these people share a manager" without knowing who the manager is, and apply that fact once a manager appears.
Key idea
There are two kinds of facts, and each fits a different structure.
- Peers form equivalence classes. Sharing a direct manager is reflexive, symmetric and transitive, so the peer groups are disjoint sets that only ever merge. That is exactly Union-Find (disjoint set union).
- A manager belongs to a whole group, not to one person. Keep a map
manager[root] = manager_idkeyed by the group's root. Once any member has a known manager, all current and future members report to that manager.
The operations become:
add_manager(a, b): find the root ofb's group and set its manager toa.add_peer(a, b): union the two groups. If only one group had a known manager, the merged group inherits it.is_manager(a, b): climb the chain.- Find the manager
mofb's group. - If
m == a, return true. - Otherwise repeat the step starting from
m. - If a group has no known manager, return false.
- Find the manager
On the example, add_manager("m","x") sets manager[find(x)] = m. add_peer("x","y") merges y into that group. The group root still maps to m, so is_manager("m","y") is true. If the calls arrive in the opposite order, the later add_manager simply labels the already-merged group, and the answer is the same.
Why it is correct
- Peers: two employees are in the same set exactly when the recorded calls imply they are peers, because Union-Find computes the transitive closure of
add_peer. - Manager lookup:
manager[find(x)]isx's direct manager whenever the calls imply one.add_managerwrites it on the current root, and a union carries it to the new root. - Chain walk: each step moves from a person to their direct manager, so
ais reached exactly whenais an ancestor ofb. - Termination: the chart is acyclic. A
seenset of visited roots guards against malformed input anyway. - Conflicts: if a merge finds two different managers, the input is inconsistent. Raising an error is a cheap safeguard.
Complexity
Let n be the number of employees and h the height of the org chart. Union-Find uses path compression and union by rank.
| Operation | Time |
|---|---|
add_peer | O(α(n)), effectively constant |
add_manager | O(α(n)) |
is_manager (any level) | O(h · α(n)) |
is_manager (direct only) | O(α(n)) |
Space is O(n) for the parent, rank and manager maps.
Trade-off: if queries vastly outnumber updates, you could cache ancestor sets per group. Any update can invalidate those caches, including a merge that changes a whole group's ancestry, so the plain walk is the better default.
Edge cases
- Unknown IDs:
is_managerreturns false. Updates register new IDs lazily. add_peer(a, a)is a no-op.- Peers recorded with no manager: the group stays manager-less until
add_manageris called on any member. - Merging a group with a manager and one without: the merged group inherits the known manager.
- Repeating
add_manager(a, b)is idempotent. - A conflicting manager for the same group raises an error.
is_manager(a, a)is false, since an acyclic chart never leads from a person back to themselves.
Common mistakes
- Storing the manager per employee, so a later
add_peeroradd_managerdoes not propagate to the rest of the group. - Dropping the manager when two groups merge because the new root had none.
- Treating
add_peeras a plain edge in a graph and running a search per query, which makes queries O(n). - Forgetting that facts can arrive in any order.
Python implementation
class OrgChart:
def __init__(self):
self._parent = {} # employee -> parent in union-find
self._rank = {} # root -> rank
self._manager = {} # group root -> direct manager id
def _add(self, x):
if x not in self._parent:
self._parent[x] = x
self._rank[x] = 0
def _find(self, x):
root = x
while self._parent[root] != root:
root = self._parent[root]
while self._parent[x] != root: # path compression
self._parent[x], x = root, self._parent[x]
return root
def _union(self, a, b):
ra, rb = self._find(a), self._find(b)
if ra == rb:
return
ma = self._manager.pop(ra, None)
mb = self._manager.pop(rb, None)
if ma is not None and mb is not None and ma != mb:
raise ValueError("Peers cannot have different direct managers")
if self._rank[ra] < self._rank[rb]:
ra, rb = rb, ra
self._parent[rb] = ra
if self._rank[ra] == self._rank[rb]:
self._rank[ra] += 1
merged = ma if ma is not None else mb
if merged is not None:
self._manager[ra] = merged
def add_manager(self, a, b):
self._add(a)
self._add(b)
rb = self._find(b)
existing = self._manager.get(rb)
if existing is not None and existing != a:
raise ValueError("Employee already has a different direct manager")
self._manager[rb] = a
def add_peer(self, a, b):
self._add(a)
self._add(b)
self._union(a, b)
def is_manager(self, a, b):
if a not in self._parent or b not in self._parent:
return False
seen = set()
cur = b
while True:
root = self._find(cur)
if root in seen:
return False
seen.add(root)
m = self._manager.get(root)
if m is None:
return False
if m == a:
return True
cur = m
org = OrgChart()
org.add_manager("m", "x")
org.add_peer("x", "y")
assert org.is_manager("m", "y")
org.add_manager("ceo", "m")
assert org.is_manager("ceo", "y")
assert not org.is_manager("y", "m")
For direct-only semantics, replace the loop in is_manager with return self._manager.get(self._find(b)) == a.