Problem
You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of the ith node. The root of the tree is node 0, so parent[0] = -1 since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree.
The data structure should support the following functions:
- Lock: Locks the given node for the given user and prevents other users from locking the same node. You may only lock a node using this function if the node is unlocked.
- Unlock: Unlocks the given node for the given user. You may only unlock a node using this function if it is currently locked by the same user.
- Upgrade**: Locks** the given node for the given user and unlocks all of its descendants regardless of who locked it. You may only upgrade a node if all 3 conditions are true:
- The node is unlocked,
- It has at least one locked descendant (by any user), and
- It does not have any locked ancestors.
Implement the LockingTree class:
LockingTree(int[] parent)initializes the data structure with the parent array.lock(int num, int user)returnstrueif it is possible for the user with iduserto lock the nodenum, orfalseotherwise. If it is possible, the nodenumwill become locked by the user with iduser.unlock(int num, int user)returnstrueif it is possible for the user with iduserto unlock the nodenum, orfalseotherwise. If it is possible, the nodenumwill become unlocked.upgrade(int num, int user)returnstrueif it is possible for the user with iduserto upgrade the nodenum, orfalseotherwise. If it is possible, the nodenumwill be upgraded.
Examples
Example 1:
graph TD; A(0) --- B(1) & C(2) B --- D(3) & E(4) C --- F(5) & G(6)
| |
Solution
Method 1
Code
| |
| |
Complexity
- ⏰ Time complexity:
- lock/unlock: O(1) — Both operations are simple hash map lookups and updates.
- upgrade: O(h + d)
- Checking ancestors (to root): O(h), where h is the height of the tree.
- Checking for locked descendants and unlocking them: O(d), where d is the number of descendants (in the worst case, O(n) if the tree is a chain or the node is the root).
- So, worst-case for
upgradeis O(n).
- 🧺 Space complexity:
- The
parentarray is O(n). - The
lockedmap can have up to O(n) entries. - The
childrenmap/list is O(n) for storing all children relationships.
- The