Hierarchical Permission Check
Problem statement
A company stores its permissions as a hierarchy. Each row hierarchy[i] = [parent, child] says that permission child sits directly under permission parent. Every permission has at most one parent, so the hierarchy is a forest of trees.
A user holds the permissions listed in granted. Holding a permission also gives the user every permission below it in the hierarchy: its children, their children, and so on. Holding a permission never gives the user anything above it.
A permission name that does not appear in hierarchy has no parent and no children. The user has such a permission only when it is listed in granted.
For each name in queries, decide whether the user has that permission. Return an array of booleans in the same order as queries.
granted and queries may contain repeated names.
Function
checkPermissions(hierarchy: String[][], granted: String[], queries: String[]) → boolean[]Examples
Example 1
hierarchy = [["admin","billing"],["admin","users"],["billing","refunds"],["users","invite"]]granted = ["billing"]queries = ["refunds","billing","admin","invite"]return = [true,true,false,false]The user holds billing. Its only child is refunds, so the user has billing and refunds.
adminis the parent ofbilling. A grant never moves up, so the answer isfalse.invitesits underusers, which is a different branch, so the answer isfalse.
Example 2
hierarchy = [["orders","view_orders"],["orders","edit_orders"],["reports","export"]]granted = ["orders","audit"]queries = ["edit_orders","audit","export","delete_all"]return = [true,true,false,false]edit_orders is a child of the granted orders, so it is covered.
auditis not in the hierarchy, but it is granted directly, so the answer istrue.exportsits underreports, which the user does not hold.delete_allis neither in the hierarchy nor granted, so the answer isfalse.
Example 3
hierarchy = [["a","b"],["b","c"],["c","d"]]granted = ["c","c"]queries = ["d","c","b","a","d"]return = [true,true,false,false,true]The chain is a → b → c → d. The user holds c twice, which counts the same as holding it once.
The user has c and d, but not b or a, which are above c. The repeated query d gets the same answer both times.
Constraints
0 <= hierarchy.length <= 400hierarchy[i].length == 20 <= granted.length <= 3001 <= queries.length <= 400- Every permission name has
1to20characters, and each character is a lowercase English letter or an underscore. - Every row has
parent != child. - No permission appears as the child in more than one row, and the rows contain no cycle, so the hierarchy is a forest.