Distinct Transitive Prerequisites in a Dependency DAG
Trees & GraphsAuto-graded · 21 test casesLast updated
For each node in a DAG whose links may name unknown items, count the distinct nodes reachable along link direction, counting shared descendants once.
You are given a list of distinct item names and a list of directed links between names. A link [a, b] means that a requires b.
For each item in names, count how many different items it requires, either directly or through a chain of requirements. If a requires b and b requires c, then a requires both b and c.
Precise definition
Call a link valid if both of its names appear in names. Ignore every other link completely.
For an item u, its answer is the number of distinct items v in names with v != u such that there is a sequence of valid links [u, x1], [x1, x2], ..., [xk, v] with k >= 0. Each link in the sequence starts at the name where the previous one ended, and the sequence follows the link direction, from the first name to the second.
The count is therefore about what u requires, never about what requires u. For [a, b], the item a gains b in its count, and b gains nothing from a.
Return a list of integers with one answer per item, in the same order as names.
Rules
- Invalid links are dropped before anything else. A dropped link takes part in no chain. Dropping it never creates a connection between the remaining items. For example, if
xrequiresghostandghostrequiresy, andghostis not innames, thenxdoes not requireyunless a chain of valid links says so. - Duplicate links may appear and have no effect on any count.
- Distinct counting. An item reachable along several different chains is counted once.
- No self-counting. An item is never counted as requiring itself. Self-links
[a, a]do not occur. - No requirements, no count. An item with no valid outgoing link has answer
0. This includes items that appear in no link at all. - Case sensitivity. Names are compared exactly, so
"a"and"A"are different items. - Acyclic input. The valid links never form a cycle.
- Empty input. If
namesis empty, return an empty list.
Task
Implement count_required_nodes(names, links), which returns the list of answers described above.
Constraints
0 <= len(names) <= 2000. All names are unique and non-empty strings.0 <= len(links) <= 10000. Each link is a list of exactly two strings.- Links with an endpoint that is not in
namesare ignored. - The graph formed by the valid links is acyclic.
Examples
Example 1
Input: count_required_nodes(['A', 'B', 'C', 'D', 'E'], [['B', 'A'], ['C', 'A'], ['D', 'B'], ['D', 'C'], ['E', 'ghost'], ['ghost', 'A']])
Output: [0, 1, 1, 3, 0]
Hints
Hint 1
Treat each valid link a -> b as a directed edge and ask which nodes you can reach by following edges forward from a node. Filter out links with unknown endpoints before building any graph.
Hint 2
Adding up the counts of a node's direct requirements overcounts when two chains share a node. Track which nodes are reachable, not just how many, and merge with a union.
Hint 3
Use Kahn's algorithm on the reversed graph so a node is handled only after everything it requires. Push each node's finished reachable set, plus the node itself, to the nodes that require it. A Python int used as a bitmask makes the union a single OR.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat each valid link [a, b] as a directed edge a -> b. The answer for a node is the number of distinct other nodes reachable from it by following edges forward.
- Map each name to an index. Keep a link only if both endpoints are known. Dropping the link entirely means no path can run through an unknown name. Deduplicate links with a set.
- Keep a bitmask
reach[v]for every node. Bituis set whenvrequiresu, directly or indirectly. - Run Kahn's topological sort on the reversed graph. A node starts with an in-degree equal to its number of distinct requirements, so it is dequeued only after everything it requires has been dequeued. Its
reachis then complete. - When a node
xis dequeued, every itempthat requiresxreceivesreach[x] | (1 << x). That is,prequiresxand everythingxrequires. - The answer for each node is the number of set bits in its mask.
Why summing child counts fails
The tempting recurrence is count(a) = sum(count(b) + 1) over the direct requirements b of a. It is only right on trees. Suppose D requires B and C, and both B and C require A. Then count(B) = count(C) = 1, so the formula gives count(D) = 2 + 2 = 4. The true answer is 3 (B, C, A), because A was counted once per path. A count says how many items there are but not which ones, so two overlapping groups cannot be merged from their sizes. On layered diamond graphs the overcount grows exponentially. Propagating identities and merging with union fixes this, because union is idempotent.
Why it is correct
Invariant: when a node x is dequeued, its reach is final and equals the set of everything x requires.
By induction on the processing order, every direct requirement y of x is dequeued before x, since x becomes ready only after all of them are done. Each y contributes reach[y] | {y}, and the union of these is exactly the set of items x requires. Nothing extra is added, because every bit travels along a real link. x never appears in its own set, because the graph is acyclic.
Filtering unknown names before building the graph guarantees that no chain passes through an unknown item.
Complexity
With V nodes and E links:
- Time:
O(V + E)for the sort, plusEOR operations onV-bit integers, aboutO(E * V / 64)word operations. - Space:
O(V^2 / 8)bytes for the masks, around 500 KB atV = 2000.
Alternatives:
- Set propagation has the same structure but needs far more time and memory because of hash-set overhead.
- A separate DFS or BFS from each node takes
O(V * (V + E))time and onlyO(V + E)memory. It needs no topological sort, and it suits tight memory or queries on only a few nodes.
Reference solution
from collections import deque
from typing import List
def count_required_nodes(names: List[str], links: List[List[str]]) -> List[int]:
index = {name: i for i, name in enumerate(names)}
n = len(names)
# A link a -> b (a requires b) is stored reversed, as b -> a, so that
# information flows from a requirement to the items that need it.
needed_by = [[] for _ in range(n)]
indegree = [0] * n # number of distinct requirements of each item
seen = set()
for a, b in links:
if a not in index or b not in index:
continue
requirer, required = index[a], index[b]
key = (required, requirer)
if key in seen:
continue
seen.add(key)
needed_by[required].append(requirer)
indegree[requirer] += 1
# reach[v] is a bitmask of everything v requires (directly or indirectly).
reach = [0] * n
queue = deque(i for i in range(n) if indegree[i] == 0)
while queue:
node = queue.popleft()
contribution = reach[node] | (1 << node)
for parent in needed_by[node]:
reach[parent] |= contribution
indegree[parent] -= 1
if indegree[parent] == 0:
queue.append(parent)
return [bin(mask).count("1") for mask in reach]