Bank app~15 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-191bit-manipulation
A banking app gives staff members roles, and each role is a permission mask. Bit i of a mask is 1 when the role holds permission i, for example "view accounts" or "approve a refund".
A member can hold several roles at once, so their permissions combine. The security team wants to know how many permissions a member has beyond the baseline that every member gets. Your team lead asks: "How many extra permissions does this member hold?"
Write new_permissions(roles, baseline).
roles is the list of masks of the member's roles. A permission held by two roles is still one permission.baseline is the mask of permissions every member already has.baseline.Input: roles = [5, 12, 3], baseline = 6
Output: 2Combine the roles with OR, so a bit is 1 if any role holds it. Then remove the baseline bits.
| Role | Binary | Union so far | Binary |
|---|---|---|---|
| 5 | 101 | 5 | 101 |
| 12 | 1100 | 13 | 1101 |
| 3 | 11 | 15 | 1111 |
The union is 15 (1111). The baseline 6 is 110, so removing its bits leaves 9 (1001), which has 2 bits set.
Input: roles = [3, 3], baseline = 0
Output: 2Two equal roles give one set of permissions, so the member holds 2 permissions, not 4.
Input: roles = [15], baseline = 15
Output: 0The baseline already covers every permission the role holds, so no permission is new.
1 ≤ len(roles) ≤ 700,0000 ≤ roles[i] < 2^300 ≤ baseline < 2^30Looking through every role for each of 64 bit positions costs 44,800,000 steps for 700,000 roles. OR combines a role into the union in one step, so one pass over the roles costs about 700,000 steps. Counting the remaining bits then costs at most 30 more.