Batch Simulation of Conflict-Free Node Locks on a Rooted Tree
Data Structure DesignAuto-graded · 18 test casesLast updated
Process a batch of lock, unlock and query operations on a rooted tree where no locked node may be an ancestor or descendant of another, using subtree ranges and Fenwick trees.
You are given a rooted tree with n nodes labeled 0 to n - 1. The tree is described by an array parent of length n, where parent[0] = -1 (node 0 is the root) and parent[i] is the parent of node i for every i > 0.
Every node starts out unlocked. You must simulate a sequence of operations and report the result of each one. The operations are given as two parallel lists: operations[j] is the name of the j-th operation and arguments[j] is a list whose first element arguments[j][0] is the node the operation targets.
The supported operations are:
"lock": Locks nodexand returnstrueonly if all of the following hold:xitself is not locked, no ancestor ofxis locked, and no descendant ofxis locked. Otherwise nothing changes and it returnsfalse."unlock": Ifxis currently locked, unlocks it and returnstrue. Otherwise nothing changes and it returnsfalse."isLocked": Returnstrueifxis currently locked,falseotherwise. It never changes any state.
Here, "ancestor" means any node on the path from the parent of x up to the root, and "descendant" means any node in the subtree of x other than x itself. Siblings and cousins never conflict with each other.
Return a list of booleans, one per operation, in the same order as the operations.
The operations are meant to be handled efficiently, so a solution that walks the whole path to the root or the whole subtree for every operation may be too slow on large inputs.
Constraints
1 <= n <= 2 * 10^5parent[0] = -1, and fori > 0,0 <= parent[i] < n; the array describes a valid tree rooted at0.- The number of operations is at most
2 * 10^5. len(operations) == len(arguments), and eacharguments[j]contains a valid node label in position0.- Each operation name is one of
"lock","unlock","isLocked". - The tree can be a long chain, so deep recursion may be a problem.
Examples
Example 1
Input: simulate_tree_locks([-1, 0, 0, 1, 1], ['lock', 'isLocked', 'lock', 'unlock', 'lock', 'isLocked'], [[0], [3], [3], [0], [1], [3]])
Output: [True, False, False, True, True, False]
Example 2
Input: simulate_tree_locks([-1, 0, 1], ['lock', 'lock', 'unlock', 'lock'], [[2], [1], [2], [1]])
Output: [True, False, True, True]
Hints
Hint 1
Flatten the tree with a DFS so that every subtree occupies one contiguous range of positions. Do it iteratively, since the tree can be 200000 levels deep.
Hint 2
Asking whether any descendant (or the node itself) is locked becomes a range-sum query over the subtree's range, which a Fenwick tree handles in O(log n).
Hint 3
To detect a locked ancestor, when locking y add +1 over y's whole subtree range using a difference array stored in a second Fenwick tree. A point query at x then counts the locked nodes whose subtree contains x. Undo the same updates on unlock.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Flatten the tree with a preorder DFS (an Euler tour). Each node x gets an entry index tin[x] and an exit index tout[x], and its subtree is exactly the half-open range [tin[x], tout[x]). The DFS is iterative so a chain of 200000 nodes does not overflow the recursion stack.
Two Fenwick trees (binary indexed trees) then answer the conflict questions in O(log n):
- Locked-node counter. Store
1at positiontin[y]for every locked nodey. The sum over[tin[x], tout[x])is the number of locked nodes in the subtree ofx, includingx. If it is positive,xor a descendant is locked. - Ancestor cover (difference array). When
yis locked, add+1attin[y]and-1attout[y]. The prefix sum at positiontin[x]is then the number of locked nodes whose subtree range containstin[x], which means the locked ancestors ofxplusxitself. If it is positive,xor an ancestor is locked.
Operations:
lock(x): succeed only ifxis not locked, the ancestor-cover query is zero and the descendant range query is zero. On success markxlocked and apply the updates to both Fenwick trees.unlock(x): ifxis locked, mark it unlocked and apply the opposite updates; otherwise returnfalsewithout touching anything.isLocked(x): read the boolean array.
Why it is correct
- In a preorder traversal, the descendants of
xare visited after enteringxand before leaving it, soyis in the subtree ofxexactly whentin[x] <= tin[y] < tout[x]. - The descendant query counts locked nodes in that range, so it is zero exactly when no locked node lies in the subtree.
- A node
yis an ancestor ofx(orxitself) exactly whentin[x]lies iny's range. The difference array adds one for each such lockedy, so the point query is zero exactly when none exists. - Locks are granted only when both counts are zero, so no two locked nodes are ever in an ancestor-descendant relationship. Unlock undoes exactly the updates made by lock, so both structures always match the current set of locked nodes.
Edge cases: locking the root has tout = n, so the -1 update at index n falls outside the Fenwick tree and is safely ignored. A repeated lock or unlock returns false and does not change the Fenwick trees. A single-node tree works, and siblings and cousins have disjoint ranges so they never conflict.
A simpler idea, keeping a locked-descendant count on every node and walking up to the root on each operation, costs O(depth) per operation, which is O(n) on a chain and too slow.
Complexity
- Preprocessing: O(n).
lockandunlock: O(log n) each.isLocked: O(1).- Total: O(n + q log n) time for q operations, and O(n) space.
Reference solution
from typing import List
class Fenwick:
def __init__(self, n):
self.n = n
self.tree = [0] * (n + 1)
def add(self, index, delta):
index += 1
while index <= self.n:
self.tree[index] += delta
index += index & -index
def prefix_sum(self, end):
total = 0
while end > 0:
total += self.tree[end]
end -= end & -end
return total
def range_sum(self, left, right):
return self.prefix_sum(right) - self.prefix_sum(left)
def simulate_tree_locks(parent: List[int], operations: List[str], arguments: List[List[int]]) -> List[bool]:
n = len(parent)
children = [[] for _ in range(n)]
for node in range(1, n):
children[parent[node]].append(node)
tin = [0] * n
tout = [0] * n
timer = 0
stack = [(0, False)]
while stack:
node, exiting = stack.pop()
if exiting:
tout[node] = timer
continue
tin[node] = timer
timer += 1
stack.append((node, True))
for child in reversed(children[node]):
stack.append((child, False))
locked = [False] * n
locked_nodes = Fenwick(n)
ancestor_cover = Fenwick(n)
results = []
for operation, args in zip(operations, arguments):
node = args[0]
if operation == "isLocked":
results.append(locked[node])
elif operation == "unlock":
if locked[node]:
locked[node] = False
locked_nodes.add(tin[node], -1)
ancestor_cover.add(tin[node], -1)
ancestor_cover.add(tout[node], 1)
results.append(True)
else:
results.append(False)
elif operation == "lock":
has_locked_ancestor = ancestor_cover.prefix_sum(tin[node] + 1) > 0
has_locked_descendant = locked_nodes.range_sum(tin[node], tout[node]) > 0
if not locked[node] and not has_locked_ancestor and not has_locked_descendant:
locked[node] = True
locked_nodes.add(tin[node], 1)
ancestor_cover.add(tin[node], 1)
ancestor_cover.add(tout[node], -1)
results.append(True)
else:
results.append(False)
else:
raise ValueError("unknown operation")
return results