- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 52 lines of Python from the credited upstream file 1993.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Node:2 def __init__(self):3 self.children: list[int] = []4 self.lockedBy = -15 6 7class LockingTree:8 def __init__(self, parent: list[int]):9 self.parent = parent10 self.nodes = [Node() for _ in range(len(parent))]11 for i in range(1, len(parent)):12 self.nodes[parent[i]].children.append(i)13 14 def lock(self, num: int, user: int) -> bool:15 if self.nodes[num].lockedBy != -1:16 return False17 self.nodes[num].lockedBy = user18 return True19 20 def unlock(self, num: int, user: int) -> bool:21 if self.nodes[num].lockedBy != user:22 return False23 self.nodes[num].lockedBy = -124 return True25 26 def upgrade(self, num: int, user: int) -> bool:27 if self.nodes[num].lockedBy != -1:28 return False29 if not self._anyLockedDescendant(num):30 return False31 32 33 i = num34 while i != -1:35 if self.nodes[i].lockedBy != -1:36 return False37 i = self.parent[i]38 39 self._unlockDescendants(num)40 self.nodes[num].lockedBy = user41 return True42 43 def _anyLockedDescendant(self, i: int) -> bool:44 return (self.nodes[i].lockedBy != -1 or45 any(self._anyLockedDescendant(child)46 for child in self.nodes[i].children))47 48 def _unlockDescendants(self, i: int) -> None:49 self.nodes[i].lockedBy = -150 for child in self.nodes[i].children:51 self._unlockDescendants(child)52