progress

~/problems / Trees / Tree DP

Count subordinates in a company tree

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

Implement subordinates(n, bosses) -> list[int].

A company has employees 1..n; employee 1 is the director. bosses[i] is the direct boss of employee i + 2, so the reporting lines form a tree rooted at 1. A boss's number can be larger than their employee's.

Return a list whose k-th entry (0-based) is the number of subordinates of employee k + 1: everyone below them, direct or indirect.

subordinates(5, [1, 1, 2, 3])
# employee 2's boss is 1, 3's boss is 1, 4's boss is 2, 5's boss is 3
# [4, 1, 1, 0, 0]
An org chart with director 1 over employees 2 and 3, 4 under 2 and 5 under 3; badges show 4 subordinates for the director, 1 each for employees 2 and 3, and 0 for 4 and 5

n goes up to 100,000.

⭐ Bonus: a speed test on a 100,000-employee chain earns a star in O(n) without recursion. Walking up to the root from every employee is O(n²) there.

Show hint

A count is easy once all direct reports' counts are known. Find an order where everyone comes after their boss, then process it in reverse.

Topic: Tree DP. Post-order: each node returns a small tuple of states to its parent.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc