Letter Access Sets Through a Dependency Graph
Trees & GraphsAuto-graded · 23 test casesLast updated
Tests topological processing of a DAG where each node computes an active letter set from its parents' resolved sets plus its own additions and removals.
You are building an access control system modeled as a directed acyclic graph of n nodes numbered 0 to n - 1. Each letter of the lowercase alphabet represents one type of access.
A directed edge [u, v] means node u is a predecessor of node v, and v receives letters from u. On top of what it receives, each node i carries two letter strings:
grant[i]: letters this node adds to its active set.block[i]: letters this node removes from its active set.
Computing a node's active set
- Collect the active sets of every direct predecessor and take their union. If the node has no predecessors, this union is the empty set.
- Add every letter in
grant[i]. - Remove every letter in
block[i].
The result is the node's active set. This is the only thing the node forwards to its successors — its own grant and block strings are not passed on. A letter that was removed at some earlier node can therefore reappear at a later one, either because a different predecessor still carries it, or because the later node adds it through its own grant.
Return the active set of every node as a list of n strings, where element i represents node i's active set. Each string must contain the letters in ascending alphabetical order with no duplicates. A node whose active set is empty maps to "".
Note: node indices do not necessarily appear in topological order, so a predecessor may carry a higher index than its successor.
Constraints
1 <= n <= 100 0000 <= len(edges) <= 200 000- Each edge is
[u, v]with0 <= u, v <= n - 1,u != v. No edge appears more than once. - The graph is guaranteed to contain no directed cycle.
len(grant) == len(block) == n- Each
grant[i]andblock[i]is a string of 0 to 26 distinct lowercase English letters in any order. - For every node
i,grant[i]andblock[i]share no letter.
Examples
Example 1
Input: compute_active_sets(4, [[0, 1], [0, 2], [1, 3], [2, 3]], ['ab', 'c', '', 'd'], ['', 'a', 'b', ''])
Output: ['ab', 'bc', 'a', 'abcd']
Example 2
Input: compute_active_sets(3, [[0, 1], [1, 2]], ['xy', '', 'x'], ['', 'xy', ''])
Output: ['xy', '', 'x']
Example 3
Input: compute_active_sets(3, [[2, 0], [1, 0]], ['m', 'qp', 'r'], ['q', '', ''])
Output: ['mpr', 'pq', 'r']
Hints
Hint 1
A node's active set can only be finalized once every one of its predecessors has been finalized. What classic graph algorithm visits nodes in exactly that order?
Hint 2
There are at most 26 distinct letters, so any active set fits inside a single integer as a bitmask. Union becomes bitwise OR, adding letters becomes OR, and removing letters becomes AND with a bitwise complement.
Hint 3
When you finalize a node's bitmask, push that single integer to each of its successors — not the grant/block rules. Track a running OR of received masks per node so you can finalize it the moment its last predecessor is done.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Topological order is mandatory
Each node's active set depends on the fully resolved sets of all its predecessors. Node indices carry no ordering guarantee — a predecessor can have a larger index than its successor — so you cannot simply iterate 0..n-1. Instead, use Kahn's algorithm: maintain a count of unresolved predecessors for each node, start with nodes whose count is zero, and enqueue each successor the moment its count drops to zero. This guarantees every node is finalized only after all its predecessors are done.
Bitmask representation
The alphabet is fixed at 26 letters, so any active set fits in a 26-bit integer where bit b corresponds to the letter chr(97 + b). This compresses every set operation to a single CPU instruction:
| Operation | Bitmask equivalent |
|---|---|
| Union of parent sets | bitwise OR across parent masks |
Add grant[i] | OR with the grant mask |
Remove block[i] | AND with the bitwise complement of the block mask |
For a node u, the formula is:
active[u] = (inherited[u] | grant_mask[u]) & ~block_mask[u]
inherited[v] is the running OR of all finalized predecessors' masks for node v. Each time a predecessor u is finalized, inherited[v] |= active[u].
Only the final mask flows downstream
After active[u] is computed, only that integer is OR'd into each successor's inherited accumulator. The grant and block masks of u are never forwarded. This is what allows a letter removed at node u to reappear at a downstream node, either because another predecessor still carries it, or because the downstream node adds it through its own grant.
Order of operations matters
The union of parents is formed first, then the node's own additions, then its own removals. Applying removals before the union would give wrong answers when one predecessor removes a letter that another predecessor still carries.
Why & ~bm[u] is safe in Python
Python integers have arbitrary precision, so ~bm[u] is a negative value with infinitely many leading 1 bits. ANDing it with a non-negative mask still clears exactly the blocked bits and leaves a non-negative result, with no need for an explicit 0x3FFFFFF mask.
Converting masks back to strings
Read bits 0 through 25 in order and emit the corresponding letter for each set bit. Ascending order comes for free. A small dictionary cache avoids re-rendering the same mask more than once, which helps when many nodes share an identical active set.
Correctness argument
Kahn's algorithm dequeues a node only after all its incoming edges have been consumed, which means all predecessor masks have already been OR'd into inherited[u]. The formula then matches the problem definition exactly. Because the input is guaranteed to be a DAG, every node eventually reaches in-degree zero and is processed.
Edge cases
- No edges: every node is its own source; its active set is just its
grantletters sorted. - Unsorted grant/block strings: reading bits in index order produces sorted output regardless of input order.
- Empty active set: the mask is
0, which produces"". - Blocking a letter the node never had: clearing an already-zero bit is a no-op.
- Diamond (multiple common ancestors):
inheritedaccumulates correctly via OR across all predecessors. - Long chains (
n = 100 000): the iterative queue avoids Python's recursion depth limit.
Complexity
- Time: O(n + m + L), where
mis the number of edges andLis the total length of all grant/block strings (at most 52n). Each edge triggers one O(1) OR. Converting masks to strings costs O(26) per distinct mask; the cache means each unique mask is rendered at most once. - Space: O(n + m) for the adjacency lists, in-degree array, and inherited/active arrays, plus O(n) for the output strings.
Full solution
from typing import List
def compute_active_sets(n: int, edges: List[List[int]], grant: List[str], block: List[str]) -> List[str]:
# Build successor lists and track how many predecessors each node has.
successors = [[] for _ in range(n)]
indeg = [0] * n
for u, v in edges:
successors[u].append(v)
indeg[v] += 1
# Encode each letter string as a 26-bit integer mask.
# Bit b is set when the letter chr(97 + b) is present.
letter_bit = {chr(97 + b): 1 << b for b in range(26)}
gm = [sum(letter_bit[c] for c in s) for s in grant]
bm = [sum(letter_bit[c] for c in s) for s in block]
# inherited[v] accumulates the OR of all finalized predecessors' masks.
inherited = [0] * n
active = [0] * n
# Kahn's algorithm: start with nodes that have no predecessors.
queue = [i for i in range(n) if indeg[i] == 0]
for u in queue:
# Finalize this node: union of parents, then add grant, then remove block.
f = (inherited[u] | gm[u]) & ~bm[u]
active[u] = f
# Push only the final mask to each successor.
for v in successors[u]:
inherited[v] |= f
indeg[v] -= 1
if indeg[v] == 0:
queue.append(v)
# Convert each bitmask back to a sorted letter string, caching results.
alphabet = 'abcdefghijklmnopqrstuvwxyz'
cache: dict[int, str] = {}
result = []
for f in active:
s = cache.get(f)
if s is None:
s = ''.join(alphabet[b] for b in range(26) if f >> b & 1)
cache[f] = s
result.append(s)
return result