Inherited Permissions Across a Group Hierarchy
Trees & GraphsAuto-graded · 21 test casesLast updated
Answer permission queries over a DAG of groups where each group inherits from its parents, using graph traversal with memoization or caching.
Inherited Permissions Across a Group Hierarchy
A platform organizes its user groups into a hierarchy shaped like a directed acyclic graph (DAG). A group automatically gets every permission held by any of its parent groups, and this carries up through any number of levels.
You are given three inputs:
edges: a list of[child, parent]pairs. Each pair meanschildinherits fromparent. A group may appear in several pairs, so it can have multiple parents and multiple children.direct_grants: a list of[group, permission]pairs. Each pair meansgroupwas explicitly givenpermission.queries: a list of operations. Each operation is a list of strings whose first element is the operation name.- An operation of the form
["has_permission", group, permission]is a check. - Any operation whose name is not
"has_permission"must be ignored. It produces no output.
- An operation of the form
A group holds a permission if either:
- the permission was granted directly to that group, or
- at least one of its parents holds the permission (recursively, so grandparents and higher ancestors count).
Task
Implement a function that processes queries in order and returns a list of booleans, one for each "has_permission" operation, in the same order. Each value is True if the given group holds the given permission, and False otherwise.
Rules
- A group or permission that never appears in the inputs is valid. Such a group has no parents and no grants, so the answer is
False. - Permissions flow only upward from parent to child. A parent never receives permissions granted to its children.
- Groups in separate, disconnected parts of the hierarchy do not affect each other.
- The hierarchy is guaranteed to contain no cycles.
Constraints
0 <= len(edges) <= 10,0000 <= len(direct_grants) <= 5,000- The graph formed by
edgesis a DAG. - Group and permission names are strings.
- Chains of inheritance can be long, so make sure deep hierarchies do not crash your solution.
Examples
Example 1
Input: resolve_permissions([['admin', 'user'], ['manager', 'user']], [['user', 'view_ads']], [['has_permission', 'admin', 'view_ads'], ['has_permission', 'manager', 'edit_campaign']])
Output: [True, False]
Example 2
Input: resolve_permissions([['campaign_manager', 'manager'], ['manager', 'advertiser'], ['advertiser', 'user']], [['user', 'view_ads'], ['advertiser', 'edit_campaign']], [['has_permission', 'campaign_manager', 'view_ads'], ['has_permission', 'campaign_manager', 'edit_campaign'], ['has_permission', 'user', 'edit_campaign']])
Output: [True, True, False]
Example 3
Input: resolve_permissions([['a', 'root'], ['b', 'root'], ['c', 'a'], ['c', 'b']], [['root', 'read'], ['b', 'write']], [['has_permission', 'c', 'read'], ['has_permission', 'c', 'write'], ['has_permission', 'a', 'write']])
Output: [True, True, False]
Hints
Hint 1
Queries only ever move from a group toward its ancestors, so store each group's list of parents rather than its children.
Hint 2
A group holds a permission if it was granted directly, or if any parent holds it. Keep the direct grants in a hash set of (group, permission) pairs for constant-time lookup.
Hint 3
Diamond shapes let many paths reach the same ancestor. Cache the result for each (group, permission) pair, or use a visited set per query, so no state is explored twice. Consider an explicit stack if the chain could be very deep.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A group holds a permission if it was granted directly, or if any of its parents holds it. So a query for (group, permission) is really a question: is there any ancestor of group (including the group itself) with a direct grant of permission?
- Build a map from each group to its list of parents. Queries only move upward, so this is the only direction we need.
- Put all direct grants into a set of
(group, permission)pairs for constant-time checks. - For each
has_permissionquery, run a depth-first search starting at the group and moving to parents. Stop as soon as a node with a direct grant of the permission is found. - Use a visited set within a query so shared ancestors (diamonds) are visited once.
- Cache results. If a search fails, every visited node is an ancestor of the start (or the start itself), and none of them holds the permission. So all of them are cached as
False. If a search succeeds, only the starting group is cached asTrue, since other visited nodes are not guaranteed to hold the permission. - Operations with a name other than
has_permissionare skipped.
An explicit stack is used instead of recursion, so a chain of 10,000 edges cannot overflow Python's recursion limit.
Why it is correct
The set of nodes the DFS can reach is exactly the set of ancestors of the starting group, plus the group itself. The search returns True precisely when one of them has a direct grant of the permission, which matches the recursive definition of holding a permission. The visited set guarantees termination and prevents repeated work on shared ancestors. A failed search means no ancestor of the start holds the permission. Every visited node's own ancestors are a subset of the start's ancestors, so each visited node also lacks it, which makes the False caching sound. Unknown groups have no parents and no grants, so they naturally return False.
Complexity
- Building:
O(E + G)time and space. - Each query:
O(V + E)in the worst case for its search. CachedFalseresults and repeated queries are answered inO(1). - Space:
O(E + G)for the structures, plus the cache and the stack.
Reference solution
from typing import List
def resolve_permissions(edges: List[List[str]], direct_grants: List[List[str]], queries: List[List[str]]) -> List[bool]:
parents = {}
for child, parent in edges:
parents.setdefault(child, []).append(parent)
granted = set((g, p) for g, p in direct_grants)
memo = {}
def holds(group, permission):
key = (group, permission)
if key in memo:
return memo[key]
# Iterative DFS over ancestors to avoid recursion limits.
found = False
visited = {group}
stack = [group]
while stack:
node = stack.pop()
if (node, permission) in granted:
found = True
break
if memo.get((node, permission)) is True:
found = True
break
for par in parents.get(node, []):
if par not in visited:
visited.add(par)
stack.append(par)
# If found, only the starting group is guaranteed to hold it.
# If not found, every visited node (all ancestors) lacks it.
if found:
memo[key] = True
else:
for node in visited:
memo[(node, permission)] = False
return found
results = []
for op in queries:
if op and op[0] == "has_permission":
results.append(holds(op[1], op[2]))
return results