Subtree Access Rights Simulator for Advertiser Groups
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate a log of grant, revoke and check operations on a rooted group tree, where a grant on a node also covers every node beneath it.
Subtree Access Rights
A company organizes its groups into a rooted tree, such as World -> Country -> City. The tree is described by a dictionary parent_of that maps each group name to the name of its parent group. The root maps to None.
Advertisers can receive access rights on any group. A right given on a group also applies to every group below it in the tree.
You are given a log of operations to run in order. The log is split into two parallel lists, ops and args. For each index i, ops[i] is the operation name and args[i] is a two-element list [advertiser, group].
There are three kinds of operation:
"grant_access": record a direct right foradvertiserongroup. Granting a right that already exists changes nothing."revoke_access": remove the direct right ofadvertiseron exactlygroup. If that direct right does not exist, nothing changes. Revoking never touches rights held on other groups, whether ancestors or descendants."check_access": decide whetheradvertisercurrently has access togroup. Access exists if the advertiser holds a direct right ongroupitself or on any of its ancestors up to the root. Otherwise there is no access.
Return a list with one entry per operation, in the same order. Use None for each grant and revoke, and True or False for each check.
Notes
- Only direct rights are stored. Whether access is inherited is decided at check time, so revoking a right on a descendant does not remove access that comes from an ancestor.
- A direct right is either present or absent. Granting twice and revoking once leaves it absent.
- Every group named in a check appears as a key in
parent_of.
Constraints
- The number of operations is at most about 10^5.
- The tree has at most about 10^5 groups, and its depth is at most about 10^3.
- Group and advertiser names are non-empty strings.
opsandargshave the same length, and each element ofargshas exactly two entries: advertiser first, group second.- Each operation name is one of
"grant_access","revoke_access","check_access". - Grant and revoke should take expected O(1) time, and check should take O(depth) time.
Examples
Example 1
Input: simulate_group_access({'World': None, 'Country': 'World', 'City': 'Country'}, ['grant_access', 'check_access', 'check_access', 'revoke_access', 'check_access'], [['a', 'Country'], ['a', 'City'], ['a', 'World'], ['a', 'Country'], ['a', 'City']])
Output: [None, True, False, None, False]
Example 2
Input: simulate_group_access({'root': None, 'north': 'root', 'south': 'root', 'town': 'north'}, ['grant_access', 'check_access', 'grant_access', 'check_access', 'revoke_access', 'check_access'], [['x', 'north'], ['x', 'town'], ['y', 'root'], ['y', 'south'], ['y', 'root'], ['y', 'south']])
Output: [None, True, None, True, None, False]
Hints
Hint 1
Keep only what was explicitly granted, for example a dictionary from advertiser to a set of groups. Do not copy rights down to descendants.
Hint 2
To answer a check, start at the queried group and move to its parent repeatedly until you pass the root. Stop with True as soon as one visited group is in the advertiser's direct set.
Hint 3
Revoke should just discard the group from the advertiser's set, and it must be harmless if the group or the advertiser is unknown. Inheritance is computed on demand, so overlapping grants never need special handling.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Store only the rights that were explicitly granted, and work out inheritance only when a check is made.
- Keep a dictionary
directthat maps each advertiser to the set of groups on which they hold a direct right. - For
grant_access, add the group to the advertiser's set. Because it is a set, repeated grants are harmless. - For
revoke_access, discard the group from the advertiser's set if the set exists. If the set becomes empty, remove the advertiser's entry. Revoking a missing right does nothing. - For
check_access, begin at the queried group and followparent_oflinks up to the root. If any visited group is in the advertiser's set, returnTrue. If the walk passes the root, returnFalse.
Why it is correct
- After every operation,
direct[a]equals exactly the set of groups where advertiseracurrently holds a direct right. Grants insert, revokes remove only that one group, and there is no other state. - Access to group
gmeans a direct right exists on some node of the path fromgup to the root. The check visits exactly those nodes, so it returnsTrueprecisely when the path meets the advertiser's direct set. - Since inheritance is never stored, revoking on a descendant cannot cancel an ancestor's right. Revoking on an ancestor cannot cancel a separate right on a descendant either.
Complexity
- Grant and revoke: expected O(1) each (one hash-set operation).
- Check: O(D), where D is the tree depth, with one parent hop and one O(1) set lookup per level.
- Total time: O(Q * D) for Q operations in the worst case.
- Space: O(G) for G active direct rights, in addition to the input tree.
Reference solution
from typing import Dict, List, Optional
def simulate_group_access(parent_of: Dict[str, Optional[str]], ops: List[str], args: List[List[str]]) -> List[Optional[bool]]:
direct = {} # advertiser -> set of groups with a direct right
results = []
for op, pair in zip(ops, args):
advertiser, group = pair
if op == "grant_access":
direct.setdefault(advertiser, set()).add(group)
results.append(None)
elif op == "revoke_access":
held = direct.get(advertiser)
if held is not None:
held.discard(group)
if not held:
del direct[advertiser]
results.append(None)
else: # check_access
held = direct.get(advertiser, ())
node = group
allowed = False
while node is not None:
if node in held:
allowed = True
break
node = parent_of[node]
results.append(allowed)
return results