KatInterview

Aggregate User Permissions Through Account Ancestry

Trees & GraphsAuto-graded · 17 test cases
MediumAuto-gradedTrees & Graphsgraphstreesbfs

Last 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