#3482

Analyze Organization Hierarchy

Hard
DatabaseHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using a single pass to build a hierarchy tree allows us to calculate levels, team sizes, and salary budgets efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a mapping of employees to their direct reports.
  2. 2Step 2: Perform a depth-first search (DFS) to calculate levels, team sizes, and salary budgets in one traversal.
  3. 3Step 3: Store results in a structured format for output.
solution.py11 lines
1def analyze_hierarchy(employees):
2    from collections import defaultdict
3    tree = defaultdict(list)
4    for emp in employees:
5        tree[emp.manager_id].append(emp)
6    def dfs(emp):
7        level = 1 if emp.manager_id is None else dfs(emp.manager_id) + 1
8        size = sum(dfs(child) for child in tree[emp.employee_id]) + 1
9        budget = emp.salary + sum(dfs(child) for child in tree[emp.employee_id])
10        return level, size, budget
11    return [dfs(emp) for emp in employees]

Complexity note: The complexity is linear as we traverse each employee once to build the hierarchy and calculate metrics.

  • 1Understanding tree structures is crucial for hierarchy problems.
  • 2Recursive depth-first search can simplify complex aggregations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.