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 depth 0 has no prefix, direct reports of the root have "....", and depth-2 employees have "........".
  • mode == 1 (Two-Hop Reporting Pairs): Return "manager,employee" strings (separated by one comma and zero spaces) for every pair where employee sits exactly two management links below manager (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 mode is neither 0 nor 1, raise ValueError.
  • If relations is 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 1 and 2,000 distinct 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

  1. 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 to 2,000 employees:

    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
                                       ........Omar
    

    Watch 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.

  2. Build the adjacency map and find the hidden root

    To navigate down from any manager to their reports in O(1) dictionary lookup time, store children_by_manager: Dict[str, List[str]] mapping each manager to list(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 from row[1:] into a set has_manager, then scan the row heads row[0] for the one person not in has_manager. (Even in a 1-person chart [["Founder"]], "Founder" heads that single row and never appears in has_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_manager
    
  3. Traverse 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 is 1,000 frames, so recursion crashes with RecursionError.

    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_nodes
    
  4. Mode 0 and Mode 1: separate absolute depth from 2-edge distance

    Once preorder_nodes gives every (employee, depth) in preorder, the two modes separate cleanly:

    • Mode 0 (rendering) uses each employee's absolute depth from the root: "...." * depth + employee. At depth = 0, "...." * 0 is "", 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 for loops (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 as skip_report at most once across the entire run, and each children_by_manager[x] list is scanned at most twice (once when x is manager, once when x is direct_report).

  5. 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"]
    
  6. Analyze time and space, including output string sizes

    Let n be the number of employees and m be 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 and O(n) space — one pass populates children_by_manager and has_manager, and a second scan over row heads finds root.
    • Preorder traversal: O(n) time and O(n) space — each of the n employees is pushed and popped once.
    • Mode 0 (rendering): O(n + L_0) time and space, where L_0 = sum(4 * depth + len(name)) is the total number of characters in the returned strings. For a balanced or shallow chart L_0 is linear, whereas for a 2,000-person chain depths run 0, 1, ..., 1999 and the dots alone reach 4 * (1999 * 2000 / 2) = 7,996,000 characters (O(n^2) worst-case output size).
    • Mode 1 (two-hop pairs): O(n + L_1) time and space. There are at most n - 2 pairs (one per employee at depth >= 2). Because one grandparent's name can repeat across up to n - 2 grandchildren, L_1 is bounded by O(n * max_name_length) characters.
  7. 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, 12 dots); Mode 1 returns ["Nora,Tess", "Kai,Jude"], catching implementations that accidentally include 3-edge pairs like "Nora,Jude"; the 2,000-node chain catches recursive RecursionError.
    • 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 assuming relations[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.
  8. 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 and O(n) space. We read every name in the input rows once to build the children_by_manager dictionary and the has_manager set, then scan at most n row heads with O(1) set lookups to locate the root.
  • Preorder traversal (preorder_with_depth): O(n) time and O(n) space. Every employee is pushed onto and popped from the stack exactly once, and both stack and preorder_nodes hold at most n tuples.
  • Mode 0 rendering: O(n + L) time and space, where L is O(n^2) in the worst case. Allocating each string copies 4 * depth + len(name) characters; in a shallow chart L grows linearly with input text, whereas in a 2,000-employee single-file chain the dot prefixes sum to 4 * (0 + 1 + ... + 1999) = 7,996,000 characters, so building the output strings dominates the runtime.
  • Mode 1 two-hop pairs: O(n + L) time and space, where L is O(n * max_name_len). Each employee has at most one parent and one grandparent, so the inner loop executes at most n - 2 times across the entire traversal, and each pair copies len(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 depth 0, returning ["Founder"] in Mode 0 and [] in Mode 1.
  • Root row not at index 0: inferring the root via candidate not in has_manager works 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, because children_by_manager.get(name, []) defaults to [].
  • 2,000-employee deep chain: handled safely without RecursionError by the explicit stack, while testing that Mode 1 stops at 2 edges (Nora,Tess and Kai,Jude, never Nora,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 visits Lin's subtree before dev_lead's subtree; always push reversed(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) + 2 across 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 >= 2 instead of == 2. Two-hop pairs include grandchildren only, never great-grandchildren.
  • Claiming Mode 0 is unconditionally O(n) time. Constructing strings of length 4 * depth makes 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] = manager in O(m) time and look up grandparent = parent.get(parent.get(emp)) for each employee; this finds the exact set of pairs in O(n), though you still need a preorder walk and grouping step to satisfy the required output order, so walking manager -> direct_report -> skip_report directly 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 in has_manager (catching zero roots or multiple disconnected trees), and check after preorder_with_depth that len(preorder_nodes) equals the total number of distinct employee names. If a disconnected cycle like X -> Y -> X hides alongside a valid root VP, neither X nor Y will ever be reached from VP, so the visited-count check catches it in O(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 path list during DFS so that when visiting employee at depth d >= k, their exact k-level ancestor is path[d - k] in O(1) time. Append employee to a bucket descendants_at_k[path[d - k]] during that single traversal, and then iterate managers in preorder_nodes to emit each manager's bucket in the exact required order in O(n + output_size) time.
  • How would your data structures change for a 500,000-employee directory experiencing frequent reorganizations? Store each employee's manager_id and ordered position_index in 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 via children_by_manager in time proportional to just that manager's two-level team size.

Follow-up questions

Similar questions

More Snapchat interview questions

All 94 Snapchat questions →