Net Access Letters Across a Dependency Hierarchy
Trees & GraphsAuto-graded · 18 test casesLast updated
Compute each node's final letter set in a DAG where grants flow to all descendants but revocations apply only to the node that declares them.
Net Access Letters Across a Hierarchy
A permission system is modeled as a directed acyclic graph. Each node is an entity, and a directed edge (parent, child) means the child inherits access from the parent.
Every node can carry two optional strings of lowercase letters:
- Grants: letters this node hands out. A grant applies to the node itself and to every node reachable from it by following edges (all of its descendants).
- Revocations: letters this node removes from its own final result only. A revocation is never passed on, and it does not stop descendants from receiving the same letter through a grant made by this node or by any of its ancestors.
Rules
- A letter is available to node
vifvgrants it, or if any ancestor ofv(a node with a path tov) grants it. - The net permissions of
vare the letters available tov, minus the letters inv's own revocations. - Revocations affect only the node that declares them. Even if a parent loses a letter by revocation, a child still has that letter available if it was granted anywhere upstream.
Task
Given the graph and the grant/revocation tables, return the net permissions of every node.
Return a list of (node, permissions) pairs:
- sorted in ascending order by the node identifier, using ordinary string comparison (so
"B10"comes before"B2"), - where each
permissionsstring contains the net letters, unique and in alphabetical order, - with an empty string
""for a node whose net set is empty (it must still appear in the output).
Input
nodes: list of unique node identifier strings.edges: list of(parent, child)pairs. Both endpoints appear innodes. Duplicate edges may occur.grants: dict mapping a node identifier to a string of unique lowercase letters. A node missing from the dict has no grants.revocations: dict mapping a node identifier to a string of unique lowercase letters. A node missing from the dict has no revocations.
Output
A list of (node, permissions) pairs as described above.
Constraints
1 <= len(nodes) <= 10^40 <= len(edges) <= 2 * 10^4- Node identifiers are non-empty alphanumeric strings.
- The graph is guaranteed to be acyclic.
- All permission characters are lowercase English letters
'a'to'z'.
Examples
Example 1
Input: compute_net_permissions(['A', 'B', 'C'], [['A', 'B'], ['B', 'C']], {'A': 'rw', 'B': 'x'}, {'B': 'w'})
Output: [['A', 'rw'], ['B', 'rx'], ['C', 'rwx']]
Example 2
Input: compute_net_permissions(['U', 'V', 'W'], [['U', 'W'], ['V', 'W']], {'U': 'a', 'V': 'b', 'W': 'c'}, {'W': 'b'})
Output: [['U', 'a'], ['V', 'b'], ['W', 'ac']]
Hints
Hint 1
Keep two different quantities per node: the letters available through grants (which flow downward) and the final answer (which does not flow anywhere).
Hint 2
Process nodes in topological order so that every parent's available set is complete before it is merged into a child. Kahn's algorithm avoids recursion limits on long chains.
Hint 3
Represent each letter set as a 26-bit integer. Union is OR, removal is AND with the complement, and you can read off the letters from bit 0 to 25 to get alphabetical order.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each node has two separate quantities:
- Available letters: the union of the grants of the node and all of its ancestors. This is what flows down the graph.
- Net permissions: available letters minus the node's own revocations. This is computed once per node and never propagated.
The classic mistake is to propagate net permissions, which would let a revocation leak into descendants and violate the locality rule.
Since the alphabet has only 26 letters, each set fits in a 26-bit integer. Union is |, removal is & ~mask, and each operation is O(1).
To make sure a node's available set is final before it is pushed to its children, process nodes in topological order with Kahn's algorithm:
- Initialize
available[v]with the node's own grants. - Start the queue with all nodes of in-degree 0.
- Pop
u. For every childv, ORavailable[u]intoavailable[v], decrementv's in-degree, and enqueuevwhen it reaches 0. - Afterwards, for each node compute
available & ~removed, convert the bits from 0 to 25 into letters (this yields alphabetical order automatically), and sort the final list by node id.
Why it is correct
When a node u is popped, all its parents have already been popped and merged into it. By induction on topological order, each parent's available contains the grants of that parent and all of its ancestors. Every ancestor of u is either a parent or an ancestor of a parent, so after merging all parents, available[u] is exactly the union of grants over u and its ancestors. Sources have no ancestors, so their own grants are already correct.
Revocations are applied only at output time to the node that declared them, so they never influence descendants. Duplicate edges are harmless: each copy increments and later decrements the in-degree, and OR is idempotent. Because the graph is acyclic, every node is processed.
Complexity
- Time: O(N + E + N log N), where the sort compares node ids; parsing the permission strings and building the outputs adds at most 26 operations per node.
- Space: O(N + E) for adjacency lists, in-degrees and the masks.
Reference solution
from collections import deque
from typing import Dict, List, Tuple
def compute_net_permissions(
nodes: List[str],
edges: List[Tuple[str, str]],
grants: Dict[str, str],
revocations: Dict[str, str],
) -> List[Tuple[str, str]]:
index = {node: i for i, node in enumerate(nodes)}
n = len(nodes)
children = [[] for _ in range(n)]
indegree = [0] * n
for u, v in edges:
ui = index[u]
vi = index[v]
children[ui].append(vi)
indegree[vi] += 1
def to_mask(letters: str) -> int:
mask = 0
for ch in letters:
mask |= 1 << (ord(ch) - ord('a'))
return mask
available = [0] * n
removed = [0] * n
for node, letters in grants.items():
available[index[node]] = to_mask(letters)
for node, letters in revocations.items():
removed[index[node]] = to_mask(letters)
queue = deque(i for i in range(n) if indegree[i] == 0)
while queue:
u = queue.popleft()
for v in children[u]:
available[v] |= available[u]
indegree[v] -= 1
if indegree[v] == 0:
queue.append(v)
result = []
for i, node in enumerate(nodes):
mask = available[i] & ~removed[i]
letters = ''.join(chr(ord('a') + b) for b in range(26) if mask & (1 << b))
result.append((node, letters))
result.sort(key=lambda pair: pair[0])
return result