Engineering platform~25 min2s · 256 MBtarget O(n) time, O(n) spacetree-recursion · dfs
A team-collaboration product stores documents in nested folders. Permissions flow down the tree: a folder starts with the permissions of the folder that contains it. Then it can add permissions of its own, a grant, and take permissions away, a revoke.
Each permission is one bit of a number: 1 is read, 2 is write, 4 is share, 8 is delete, and so on. The product needs the permissions in effect on every folder, so that it can show them in the sharing screen.
Write effective_permissions(parent, grant, revoke).
i is inside folder parent[i]. Exactly one folder has parent[i] == -1: the root. The folders are numbered in no special order.grant[i] and removes the bits of revoke[i]. When a bit is in both, the revoke wins.n numbers.Input: parent = [-1, 0, 0, 1, 1, 2, 2], grant = [3, 4, 0, 0, 8, 0, 2], revoke = [0, 0, 2, 4, 0, 0, 0]
Output: [3, 7, 1, 3, 15, 1, 3]The tree has root 0, children 1 and 2 of the root, folders 3 and 4 under folder 1, and folders 5 and 6 under folder 2. The trace reads each folder after its parent.
| Folder | Parent | Inherited | Grant | Revoke | In effect |
|---|---|---|---|---|---|
| 0 | none | 0 | 3 | 0 | 3 |
| 1 | 0 | 3 | 4 | 0 | 7 |
| 2 | 0 | 3 | 0 | 2 | 1 |
| 3 | 1 | 7 | 0 | 4 | 3 |
| 4 | 1 | 7 | 8 | 0 | 15 |
| 5 | 2 | 1 | 0 | 0 | 1 |
| 6 | 2 | 1 | 2 | 0 | 3 |
The output is [3, 7, 1, 3, 15, 1, 3]. Folder 2 loses write (2) for itself and for folder 5. Folder 6 grants it back.
Input: parent = [-1, 0, 1], grant = [1, 1, 0], revoke = [0, 1, 0]
Output: [1, 0, 0]Folder 1 both grants and revokes read (1), and the revoke wins. Folder 2 inherits nothing.
Input: parent = [-1], grant = [5], revoke = [1]
Output: [4]A tree with a single folder: the grant 5 loses its read bit to the revoke 1, so the folder has 4.
1 ≤ parent.length ≤ 100,000 (folders); grant and revoke have the same lengthparent[i] is -1 for the root, and otherwise the number of another folder, so that the folders form one tree0 ≤ grant[i], revoke[i] ≤ 1,048,575 (up to 20 permission bits)Walking up to the root for every folder costs about n × depth, up to 5 × 10^9 steps for a chain of 100,000 folders. One walk down the tree from the root, passing each folder's result to its children, costs about n. The depth can reach 10^5, so a recursive walk may overflow the call stack, and an explicit stack is safer.