Aggregate User Permissions Through Account Ancestry
Trees & GraphsAuto-graded · 17 test casesLast updated
Tests hierarchical graph traversal and efficient permission accumulation using ancestor path lookup and set operations.
You're building a permission system for a multi-account platform where accounts form a tree or directed acyclic graph (DAG). Each account may have one or more parent accounts. When a user holds a role at a particular account, that role automatically applies to all accounts reachable downward in the hierarchy.
Given:
- An account hierarchy represented as
(child_account, parent_account)pairs - Direct role assignments as
(user, account, role)tuples - A list of permission queries
(user, target_account)
For each query, return all distinct roles the user possesses at the target account. A user has a role at an account if they were assigned that role either at the target account itself or at any ancestor of that account (following parent links upward).
Write a function that processes multiple queries efficiently against the same hierarchy.
Input Format:
hierarchy: List of[child, parent]pairs (both strings). Root accounts have no incoming edges.user_roles: List of[user_id, account_id, role](all strings) representing direct assignments.queries: List of[user_id, target_account_id]pairs (both strings).
Output Format:
- Return a list of sorted lists of role strings, one per query in order.
Constraints:
- 1 ≤ number of accounts ≤ 1000
- 1 ≤ number of role assignments ≤ 5000
- 1 ≤ number of queries ≤ 1000
- All identifiers are non-empty strings
- The hierarchy forms a valid DAG (no self-loops, though multiple parents are allowed)
- Role strings are case-sensitive
- If a user has no roles at the target account, return an empty list for that query
Examples
Example 1
Input: aggregate_user_permissions([['B', 'A'], ['C', 'B']], [['u1', 'A', 'admin'], ['u1', 'B', 'editor']], [['u1', 'C']])
Output: [['admin', 'editor']]
Hints
Hint 1
Build a reverse mapping from each account to its parent accounts to enable efficient upward traversal
Hint 2
Cache the ancestor list for each target account since multiple queries may reference the same target
Hint 3
Use breadth-first search with a visited set to handle DAGs correctly and avoid infinite loops if cycles exist
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that a user possesses a role at an account if they hold that role at the account itself or at any of its ancestors. This transforms each query into an ancestry lookup problem: find all ancestors of the target account, then collect the user's roles from those ancestors.
To handle multiple queries efficiently, we perform three preprocessing steps:
-
Build a parent adjacency list: Map each child account to its parent accounts. This enables efficient upward traversal through the hierarchy.
-
Index role assignments by user and account: Create a nested dictionary structure
user → account → set(roles)for O(1) lookups during queries. -
Cache ancestor lists: Since multiple queries may target the same account, cache the complete ancestor set for each target. Once computed, this list can be reused across all queries for that target.
For each query, we traverse upward from the target account using depth-first search with a visited set. The visited set serves two purposes: it handles DAG structures where an account has multiple parents (preventing duplicate processing), and it prevents infinite loops if the input unexpectedly contains cycles.
After identifying all ancestors, we iterate through them and union together all roles the user has at those accounts. The result is sorted and cached to handle duplicate queries efficiently.
Why It Works
The upward traversal starting from the target account follows parent edges transitively, visiting exactly the target plus all its ancestors. By construction, these are precisely the accounts whose roles should apply to the target through inheritance. The visited set ensures each account is processed once even in a DAG with multiple paths to the same ancestor.
Complexity
Let H = number of hierarchy edges, R = number of role assignments, Q = number of queries, d = average depth (ancestors per target), and U = number of unique targets.
- Time: O(H + R) preprocessing + O(U × d) for first-time ancestry computation + O(Q × d) for role lookups = O(H + R + (U + Q) × d)
- Space: O(H + R + U × d) for the parent map, role index, and ancestor cache
For a balanced tree, d = O(log N). For a deep chain, d can reach O(N). The caching strategy makes repeated queries on the same target very efficient.
Solution
from collections import defaultdict
from typing import List
def aggregate_user_permissions(hierarchy: List[List[str]], user_roles: List[List[str]], queries: List[List[str]]) -> List[List[str]]:
parents = defaultdict(set)
for child, parent in hierarchy:
parents[child].add(parent)
assigned = defaultdict(lambda: defaultdict(set))
for user, account, role in user_roles:
assigned[user][account].add(role)
lineage_cache = {}
result_cache = {}
results = []
for user, target in queries:
key = (user, target)
if key not in result_cache:
if target not in lineage_cache:
seen = set()
stack = [target]
while stack:
account = stack.pop()
if account in seen:
continue
seen.add(account)
stack.extend(parents.get(account, ()))
lineage_cache[target] = tuple(seen)
roles = set()
user_assignments = assigned.get(user, {})
for account in lineage_cache[target]:
roles.update(user_assignments.get(account, ()))
result_cache[key] = sorted(roles)
results.append(list(result_cache[key]))
return results