Hierarchy Tree Rendering and Two-Hop Reporting Pairs
Hard · Coding & Algorithms · Machine Learning Engineer · Onsite
Problem Statement
Given unsorted reporting rows that describe a company's management hierarchy, construct the organization tree and support two query modes through a single entry point:
def org_chart(relations: List[List[str]], mode: int) -> List[str]:
Each entry in relations has the form [manager, report_1, report_2, ...], listing manager followed by their direct reports in the exact left-to-right display order to maintain.
mode == 0(Indented Preorder View): Return one string per employee in tree preorder (visit a manager first, then completely traverse their first direct report's subtree, then their second direct report's subtree, and so on). Prepend four dots ("....") for each management hop below the top-level root, so the root at depth0has no prefix, direct reports of the root have"....", and depth-2employees have"........".mode == 1(Two-Hop Reporting Pairs): Return"manager,employee"strings (separated by one comma and zero spaces) for every pair whereemployeesits exactly two management links belowmanager(grandchildren in the hierarchy — never direct reports and never three or more links down). Visit managers in tree preorder; for each manager, scan their direct reports in stored order and, for each direct report, scan that person's direct reports in stored order.
Additional rules:
- If
modeis neither0nor1, raiseValueError. - If
relationsis empty ([]), return[]in both modes. - A single-item row
[employee]is valid and indicates an employee with zero direct reports; employees with zero direct reports may also appear only inside their manager's row without heading a row of their own. - The top-level root employee is not passed separately, and their row may appear anywhere in
relations.
Examples
Example 1
Input:
relations = [["Lin", "Omar"], ["dev_lead", "Priya", "Sam"], ["VP", "dev_lead", "Lin"]]
mode = 0
Output:
["VP", "....dev_lead", "........Priya", "........Sam", "....Lin", "........Omar"]
Explanation: "VP" is the only employee who never appears as someone else's direct report, making "VP" the root (even though "VP"'s row is last). Preorder visits "VP" (depth 0), "dev_lead" (depth 1), "Priya" and "Sam" (depth 2, keeping their input order), then "Lin" (depth 1) and "Omar" (depth 2).
Example 2
Input:
relations = [["Lin", "Omar"], ["dev_lead", "Priya", "Sam"], ["VP", "dev_lead", "Lin"]]
mode = 1
Output:
["VP,Priya", "VP,Sam", "VP,Omar"]
Explanation: Only "VP" has employees two hops below: "Priya" and "Sam" via "dev_lead", followed by "Omar" via "Lin".
Example 3
Input:
relations = [["Nora", "Kai"], ["Kai", "Tess"], ["Tess", "Jude"]]
mode = 1
Output:
["Nora,Tess", "Kai,Jude"]
Explanation: Along the four-person chain Nora -> Kai -> Tess -> Jude, "Tess" is two links below "Nora" and "Jude" is two links below "Kai". "Nora,Jude" is three links apart and is excluded. (In mode = 0, this chain produces ["Nora", "....Kai", "........Tess", "............Jude"].)
Constraints
- Valid non-empty inputs represent a single rooted tree containing between
1and2,000distinct employees (acyclic, exactly one root, and at most one manager per employee). - Every employee identifier is a non-empty ASCII string composed of letters, digits, and underscores (
_). - Each employee heads at most one row in
relations, and no row repeats the same direct report twice. - Direct-report ordering from each input row must be preserved as given (do not sort alphabetically).
Step-by-step walkthrough
Understand the input rows and the two output modes
Each row
[manager, report1, report2, ...]gives one manager followed by their direct reports in the exact display order we must keep. Together, the rows describe one rooted tree of up to2,000employees:Input rows: [["Lin", "Omar"], ["dev_lead", "Priya", "Sam"], ["VP", "dev_lead", "Lin"]] Tree & depth from root: mode == 0 (rendered) mode == 1 (two-hop pairs) depth 0: VP VP VP,Priya / \ ....dev_lead VP,Sam depth 1: dev_lead Lin ........Priya VP,Omar / \ | ........Sam depth 2: Priya Sam Omar ....Lin ........OmarWatch out for three details hidden in the specification: - The root is not supplied, and rows can arrive in any order (
"VP"is in the last row above). - Never sort direct reports: preserve the exact left-to-right order from each input row ("Priya"before"Sam","dev_lead"before"Lin"). - Two-hop / skip-level means a distance of 2 edges (manager -> direct_report -> skip_report), never 1 edge and never 3 or more edges.Build the adjacency map and find the hidden root
To navigate down from any manager to their reports in
O(1)dictionary lookup time, storechildren_by_manager: Dict[str, List[str]]mapping each manager tolist(row[1:]). Leave leaf employees who have no row of their own out of the dictionary;children_by_manager.get(name, [])will treat them as having[]reports.How do we find the root without being told who it is? Every employee except the root has a manager, which means every non-root employee appears at least once in
row[1:]. Collect all names fromrow[1:]into a sethas_manager, then scan the row headsrow[0]for the one person not inhas_manager. (Even in a 1-person chart[["Founder"]],"Founder"heads that single row and never appears inhas_manager.)from typing import Dict, List, Optional, Set, Tuple def build_tree( relations: List[List[str]], ) -> Tuple[Optional[str], Dict[str, List[str]]]: """Build ordered direct-report lists and locate the unique root employee.""" # children_by_manager: {"VP": ["dev_lead", "Lin"], "Lin": ["Omar"], ...} preserving input order children_by_manager: Dict[str, List[str]] = {} # has_manager: {"dev_lead", "Lin", "Omar", ...} — everyone who appears as someone's report has_manager: Set[str] = set() for row in relations: manager = row[0] direct_reports = list(row[1:]) children_by_manager[manager] = direct_reports for report in direct_reports: has_manager.add(report) # The root has no manager, so they never appear in has_manager. # Every valid non-empty tree puts the root at row[0] of their own row. root: Optional[str] = None for row in relations: candidate = row[0] if candidate not in has_manager: root = candidate break return root, children_by_managerTraverse in preorder with an explicit stack
Both modes visit employees in preorder: visit a manager first, then visit their first direct report's entire subtree, then their second direct report's entire subtree, and so on.
Writing preorder as a recursive function is tempting, until you test a 2,000-employee chain (
e0 -> e1 -> ... -> e1999): CPython's default call-stack limit is1,000frames, so recursion crashes withRecursionError.An explicit LIFO (last-in, first-out) stack storing
(employee, depth)avoids call-stack limits completely. Because a stack pops the last item pushed, we push a manager's direct reports in reverse order so the first direct report sits on top and gets visited next:Start: stack = [(VP, 0)] Pop (VP, 0) -> reports [dev_lead, Lin]; push reversed -> (Lin, 1), (dev_lead, 1) stack = [(Lin, 1), (dev_lead, 1)] <-- dev_lead is on top! Pop (dev_lead, 1) -> reports [Priya, Sam]; push reversed -> (Sam, 2), (Priya, 2) stack = [(Lin, 1), (Sam, 2), (Priya, 2)] Pop (Priya, 2) -> no reports; stack = [(Lin, 1), (Sam, 2)] Pop (Sam, 2) -> no reports; stack = [(Lin, 1)] Pop (Lin, 1) -> reports [Omar]; push (Omar, 2) stack = [(Omar, 2)] Pop (Omar, 2) -> no reports; stack = [] Preorder output: [(VP, 0), (dev_lead, 1), (Priya, 2), (Sam, 2), (Lin, 1), (Omar, 2)]def preorder_with_depth( root: str, children_by_manager: Dict[str, List[str]], ) -> List[Tuple[str, int]]: """Return (employee_name, depth) pairs in preorder using an explicit stack.""" preorder_nodes: List[Tuple[str, int]] = [] # Explicit LIFO stack of (employee_name, depth) avoids Python's 1,000-call # recursion limit when the org chart is a 2,000-employee chain. stack: List[Tuple[str, int]] = [(root, 0)] while stack: employee, depth = stack.pop() preorder_nodes.append((employee, depth)) direct_reports = children_by_manager.get(employee, []) # Push in reverse order so the first direct report sits on top of the LIFO # stack and gets popped (visited) first. for report in reversed(direct_reports): stack.append((report, depth + 1)) return preorder_nodesMode 0 and Mode 1: separate absolute depth from 2-edge distance
Once
preorder_nodesgives every(employee, depth)in preorder, the two modes separate cleanly:- Mode 0 (rendering) uses each employee's absolute depth from the root:
"...." * depth + employee. Atdepth = 0,"...." * 0is"", so the root has no dots. - Mode 1 (two-hop pairs) ignores absolute depth and walks two edges down from each manager (
manager -> direct_report -> skip_report):
Chain example (Example 3): Nora -> Kai -> Tess -> Jude Manager Nora -> child Kai -> grandchild Tess => "Nora,Tess" (2 edges: included) Manager Kai -> child Tess -> grandchild Jude => "Kai,Jude" (2 edges: included) Nora to Jude is 3 edges (great-grandchild) => NOT a two-hop pair!Even though Mode 1 writes three nested
forloops (manager,direct_report,skip_report), it does not take cubic time! In a tree, every employee has at most one parent (direct_report) and at most one grandparent (manager), so each employee is emitted asskip_reportat most once across the entire run, and eachchildren_by_manager[x]list is scanned at most twice (once whenxismanager, once whenxisdirect_report).- Mode 0 (rendering) uses each employee's absolute depth from the root:
Trace Examples 1 and 2 end to end
Take
relations = [["Lin", "Omar"], ["dev_lead", "Priya", "Sam"], ["VP", "dev_lead", "Lin"]]:1. build_tree: children_by_manager = {"Lin": ["Omar"], "dev_lead": ["Priya", "Sam"], "VP": ["dev_lead", "Lin"]} has_manager = {"Omar", "Priya", "Sam", "dev_lead", "Lin"} Row heads checked: "Lin" (in set), "dev_lead" (in set), "VP" (not in set -> root = "VP") 2. preorder_with_depth("VP", ...): [("VP", 0), ("dev_lead", 1), ("Priya", 2), ("Sam", 2), ("Lin", 1), ("Omar", 2)] 3. Outputs: mode == 0 -> ["VP", "....dev_lead", "........Priya", "........Sam", "....Lin", "........Omar"] mode == 1 -> manager "VP": child "dev_lead" -> "VP,Priya", "VP,Sam"; child "Lin" -> "VP,Omar" remaining employees: no grandchildren -> ["VP,Priya", "VP,Sam", "VP,Omar"]Analyze time and space, including output string sizes
Let
nbe the number of employees andmbe the total number of name entries across all input rows (m < 2n, because each employee heads at most one row and appears as a direct report at most once).- Building the tree:
O(m)time andO(n)space — one pass populateschildren_by_managerandhas_manager, and a second scan over row heads findsroot. - Preorder traversal:
O(n)time andO(n)space — each of thenemployees is pushed and popped once. - Mode 0 (rendering):
O(n + L_0)time and space, whereL_0 = sum(4 * depth + len(name))is the total number of characters in the returned strings. For a balanced or shallow chartL_0is linear, whereas for a 2,000-person chain depths run0, 1, ..., 1999and the dots alone reach4 * (1999 * 2000 / 2) = 7,996,000characters (O(n^2)worst-case output size). - Mode 1 (two-hop pairs):
O(n + L_1)time and space. There are at mostn - 2pairs (one per employee at depth>= 2). Because one grandparent's name can repeat across up ton - 2grandchildren,L_1is bounded byO(n * max_name_length)characters.
- Building the tree:
Test cases for single root, chain, and branching trees
Each key tree shape targets a distinct bug class:
- Empty chart
[]and single root[["Founder"]]:[]returns[]in both modes without crashing on a missing root;[["Founder"]]returns["Founder"]in Mode 0 and[]in Mode 1, catching code that assumes every row has at least two elements or at least one pair. - Chain
[["Nora", "Kai"], ["Kai", "Tess"], ["Tess", "Jude"]](plus a 2,000-node chain): Mode 0 checks cumulative dot prefixes (0, 4, 8, 12dots); Mode 1 returns["Nora,Tess", "Kai,Jude"], catching implementations that accidentally include 3-edge pairs like"Nora,Jude"; the 2,000-node chain catches recursiveRecursionError. - Branching tree with shuffled rows and unsorted sibling names: e.g.
[["R", "z", "a", "m"], ["z", "q"], ["a", "b"]]or deeper multi-branch charts with the root row placed last. Catches assumingrelations[0][0]is the root, sorting sibling lists alphabetically, pushing stack children in forward order, or emitting managers in BFS level order instead of preorder.
- Empty chart
Complete solution
from typing import Dict, List, Optional, Set, Tuple def build_tree( relations: List[List[str]], ) -> Tuple[Optional[str], Dict[str, List[str]]]: """Build ordered direct-report lists and locate the unique root employee.""" # children_by_manager: {"VP": ["dev_lead", "Lin"], "Lin": ["Omar"], ...} preserving input order children_by_manager: Dict[str, List[str]] = {} # has_manager: {"dev_lead", "Lin", "Omar", ...} — everyone who appears as someone's report has_manager: Set[str] = set() for row in relations: manager = row[0] direct_reports = list(row[1:]) children_by_manager[manager] = direct_reports for report in direct_reports: has_manager.add(report) # The root has no manager, so they never appear in has_manager. # Every valid non-empty tree puts the root at row[0] of their own row. root: Optional[str] = None for row in relations: candidate = row[0] if candidate not in has_manager: root = candidate break return root, children_by_manager def preorder_with_depth( root: str, children_by_manager: Dict[str, List[str]], ) -> List[Tuple[str, int]]: """Return (employee_name, depth) pairs in preorder using an explicit stack.""" preorder_nodes: List[Tuple[str, int]] = [] # Explicit LIFO stack of (employee_name, depth) avoids Python's 1,000-call # recursion limit when the org chart is a 2,000-employee chain. stack: List[Tuple[str, int]] = [(root, 0)] while stack: employee, depth = stack.pop() preorder_nodes.append((employee, depth)) direct_reports = children_by_manager.get(employee, []) # Push in reverse order so the first direct report sits on top of the LIFO # stack and gets popped (visited) first. for report in reversed(direct_reports): stack.append((report, depth + 1)) return preorder_nodes def org_chart(relations: List[List[str]], mode: int) -> List[str]: """Render preorder org lines (mode 0) or list 2-edge skip-level pairs (mode 1).""" if mode not in (0, 1): raise ValueError("mode must be 0 or 1") if not relations: return [] root, children_by_manager = build_tree(relations) if root is None: raise ValueError("invalid relations: every employee has a manager (no root)") preorder_nodes = preorder_with_depth(root, children_by_manager) result: List[str] = [] if mode == 0: # Prefix each employee with four dots per level below the root (depth 0 -> ""). for employee, depth in preorder_nodes: result.append(("...." * depth) + employee) else: # Skip-level means grandchildren (2 edges down), not all deeper descendants. # Although 3 loops are nested, each employee has at most 1 parent and 1 # grandparent, so the inner body runs at most n - 2 times total. for manager, _depth in preorder_nodes: for direct_report in children_by_manager.get(manager, []): for skip_report in children_by_manager.get(direct_report, []): result.append(f"{manager},{skip_report}") return result✅ Submit now — all tests should pass.
Intuition & how it works
Imagine assembling a company directory from a shuffled stack of team rosters, where each card says "Manager: DirectReport1, DirectReport2, ...". First, you find the top executive (root — the single top node of a rooted tree with no boss above them) by spotting the one person who never appears on anyone else's report list. Next, you walk down the hierarchy in preorder traversal (visiting each manager before visiting each of their direct reports' subtrees from left to right) while tracking depth (how many management links lie between the root and the current employee). For rendering, depth tells you how many "...." blocks to print; for two-hop pairs, you ignore depth from the top and simply look two links down (manager -> direct_report -> grandchild).
Several tempting shortcuts break on valid inputs. Assuming the first row's manager is the root fails as soon as rows arrive out of order; storing reports in a set or sorting them destroys the required display order; writing a recursive walk hits Python's 1,000-frame recursion limit on a 2,000-person chain; and pairing any two employees whose depths differ by 2 wrongly pairs a manager with their colleague's grandchildren.
Trace our sample input [["Lin", "Omar"], ["dev_lead", "Priya", "Sam"], ["VP", "dev_lead", "Lin"]]:
1. Everyone listed after index 0 is a direct report: has_manager = {"Omar", "Priya", "Sam", "dev_lead", "Lin"}. Checking row heads "Lin", "dev_lead", "VP" finds "VP" is not in has_manager, so "VP" is the root.
2. Using a LIFO stack (last-in, first-out list), we start with [("VP", 0)]. Popping ("VP", 0) pushes its reports in reverse — ("Lin", 1) then ("dev_lead", 1) — so "dev_lead" comes off next, visiting ("VP", 0) -> ("dev_lead", 1) -> ("Priya", 2) -> ("Sam", 2) -> ("Lin", 1) -> ("Omar", 2).
3. Mode 0 prefixes 4 * depth dots to get ["VP", "....dev_lead", "........Priya", "........Sam", "....Lin", "........Omar"], while Mode 1 walks two links down from each manager in that preorder list to emit ["VP,Priya", "VP,Sam", "VP,Omar"].
Complexity
Let n be the number of employees, m be the total number of name strings across all rows (m < 2n, because each employee heads at most one row and has at most one manager), and L be the total character length of the returned strings.
- Building the tree (
build_tree):O(m)time andO(n)space. We read every name in the input rows once to build thechildren_by_managerdictionary and thehas_managerset, then scan at mostnrow heads withO(1)set lookups to locate the root. - Preorder traversal (
preorder_with_depth):O(n)time andO(n)space. Every employee is pushed onto and popped from the stack exactly once, and bothstackandpreorder_nodeshold at mostntuples. - Mode 0 rendering:
O(n + L)time and space, whereLisO(n^2)in the worst case. Allocating each string copies4 * depth + len(name)characters; in a shallow chartLgrows linearly with input text, whereas in a 2,000-employee single-file chain the dot prefixes sum to4 * (0 + 1 + ... + 1999) = 7,996,000characters, so building the output strings dominates the runtime. - Mode 1 two-hop pairs:
O(n + L)time and space, whereLisO(n * max_name_len). Each employee has at most one parent and one grandparent, so the inner loop executes at mostn - 2times across the entire traversal, and each pair copieslen(manager) + 1 + len(skip_report)characters.
Edge cases
- Empty input
[]: returns[]immediately in both modes before attempting to find a root. - Single employee
[["Founder"]]:"Founder"is found as the root at depth0, returning["Founder"]in Mode0and[]in Mode1. - Root row not at index
0: inferring the root viacandidate not in has_managerworks regardless of row order. - Leaves with or without one-element rows: a leaf (an employee with zero direct reports) works identically whether it has an explicit
["Omar"]row or only appears inside its manager's row, becausechildren_by_manager.get(name, [])defaults to[]. - 2,000-employee deep chain: handled safely without
RecursionErrorby the explicit stack, while testing that Mode1stops at 2 edges (Nora,TessandKai,Jude, neverNora,Jude). - Non-alphabetical direct reports:
list(row[1:])preserves exact input order without sorting.
Common mistakes
- Assuming
relations[0][0]is always the root. Works on tidy hand-written examples and breaks whenever rows come from an unordered database query or shuffled input. - Pushing direct reports onto the stack in left-to-right order. Because a LIFO stack pops the most recently pushed item first, pushing
[dev_lead, Lin]forward visitsLin's subtree beforedev_lead's subtree; always pushreversed(direct_reports). - Using recursion without checking maximum tree depth. A valid 2,000-node chain exceeds CPython's default 1,000-frame recursion limit.
- Pairing nodes by
depth(w) == depth(v) + 2across the whole chart. Depth equality alone cannot tell a manager's own grandchildren apart from a colleague's grandchildren at the same level. - Emitting all descendants at distance
>= 2instead of== 2. Two-hop pairs include grandchildren only, never great-grandchildren. - Claiming Mode 0 is unconditionally
O(n)time. Constructing strings of length4 * depthmakes total character output quadratic (O(n^2)) when the tree degenerates into a chain.
Alternative approaches
- Parent-pointer map for Mode 1: build
parent[child] = managerinO(m)time and look upgrandparent = parent.get(parent.get(emp))for each employee; this finds the exact set of pairs inO(n), though you still need a preorder walk and grouping step to satisfy the required output order, so walkingmanager -> direct_report -> skip_reportdirectly is cleaner. - Recursive DFS after raising
sys.setrecursionlimit: slightly shorter code, at the cost of mutating global interpreter state and risking C-stack overflow on larger trees.
Follow-up questions
- How would you validate untrusted input rows to detect cycles, disconnected trees, or employees with two managers? Count appearances in
row[1:]so any employee with two managers is rejected immediately, verify that exactly one distinct employee never appears inhas_manager(catching zero roots or multiple disconnected trees), and check afterpreorder_with_depththatlen(preorder_nodes)equals the total number of distinct employee names. If a disconnected cycle likeX -> Y -> Xhides alongside a valid rootVP, neitherXnorYwill ever be reached fromVP, so the visited-count check catches it inO(m)time. - How would you generalize Mode 1 to emit reporting pairs separated by an arbitrary exact distance k? Maintain the current root-to-node
pathlist during DFS so that when visitingemployeeat depthd >= k, their exactk-level ancestor ispath[d - k]inO(1)time. Appendemployeeto a bucketdescendants_at_k[path[d - k]]during that single traversal, and then iterate managers inpreorder_nodesto emit each manager's bucket in the exact required order inO(n + output_size)time. - How would your data structures change for a 500,000-employee directory experiencing frequent reorganizations? Store each employee's
manager_idand orderedposition_indexin a database or in-memory adjacency structure so moving a team updates one parent pointer instead of rebuilding the whole tree. Paginate or render only expanded subtrees on demand (since full string rendering can be quadratic in depth), and answer two-hop queries per manager on the fly viachildren_by_managerin time proportional to just that manager's two-level team size.
Follow-up questions
- How would you validate untrusted input rows to detect cycles, disconnected trees, or employees with two managers?
- How would you generalize Mode 1 to emit reporting pairs separated by an arbitrary exact distance k?
- How would your data structures change for a 500,000-employee directory experiencing frequent reorganizations?
Similar questions
- Verify Binary Tree Completeness
- Count Connected Grid Islands
- Longest Ascending Path in a Grid
- Minimum Steps in an Obstacle Grid
- Minimal Nested Repeat String Compression
- Sliding Window Medians
More Snapchat interview questions
- Generalization, Regularization, and Transformer Self-Attention Medium
- Ordinary Least Squares With Cloned Observations Medium
- Mean Front-to-Rear Camera Transitions per Session Medium Pro
- Contrasting Batch and Layer Normalization Hard Pro
- Banner CTR and Session Engagement Analytics Medium Pro
- Count Enclosed Land Islands Medium Pro
- Daily Users Starting With App Launch Medium Pro
- API-Polled News Feed Aggregator Hard Pro
- Time-Series Metrics Monitoring and Alerting Platform Medium Pro
- Vertical Short-Video Feed Vending Backend Medium Pro