Distinct Gate Paths to LCA Problem
Description
LeetCode Problem 3973.
You are given an undirected tree rooted at node 0 with n nodes numbered from 0 to n - 1, represented by an array parent where parent[i] is the parent of node i.
Each node i has three types of gates, given in a 2D array gates where gates[i] = [red_i, blue_i, white_i] which represents the number of red, blue, and white gates at node i.
- Red gate: usable only with a red card.
- Blue gate: usable only with a blue card.
- White gate: usable with either card, but flips the card color when used.
Alice and Bob start at given nodes with either a red or blue card (1 = red, 0 = blue). They must independently move upward to their lowest common ancestor (LCA).
At each node, a person may move to their parent only if they can use at least one gate at that node with their current card. White gates may be used any number of times to flip the card color.
Movement rules (one move = from u to parent[u]):
- Movement is only upward toward the root.
- At node
u, pick exactly one specific gate instance. Identical gates are treated as separate and counted individually. - If holding a red card: use a red gate to remain red, or a white gate to change to blue.
- If holding a blue card: use a blue gate to remain blue, or a white gate to change to red.
- If no usable gate exists at
u, the sequence ends.
You are also given a 2D array queries where queries[i] = [aNode_i, aCard_i, bNode_i, bCard_i]:
aNode_i,aCard_i: Alice's starting node and card.bNode_i,bCard_i: Bob's starting node and card.
For each query, count the number of distinct valid ways modulo 10^9 + 7 for both to reach their LCA.
After computing the result for all queries, return the bitwise XOR of those values.
Note:
- Two ways are distinct if the set of gates used differs for either Alice or Bob.
- If any person is already at the LCA, then the number of ways for them is 1.
- The lowest common ancestor (LCA) is defined between two nodes
aandbas the lowest node in a tree that has bothaandbas descendants (where a node is allowed to be a descendant of itself).
Example 1:
Input: n = 3, parent = [-1,0,0], gates = [[1,0,1],[0,1,1],[1,1,0]], queries = [[1,0,2,0],[1,1,2,0],[1,0,2,1]]
Output: 1
Explanation:
i Alice [Node, Card] Bob [Node, Card] LCA Alice Path Bob Path Alice Ways Bob Ways Total Ways
0 [1, 0]: Blue [2, 0]: Blue 0 1 → 0 2 → 0 2 (1 Blue + 1 White at node 1) 1 (1 Blue at node 2) 2 × 1 = 2
1 [1, 1]: Red [2, 0]: Blue 0 1 → 0 2 → 0 1 (1 White at node 1) 1 (1 Blue at node 2) 1 × 1 = 1
2 [1, 0]: Blue [2, 1]: Red 0 1 → 0 2 → 0 2 (1 Blue + 1 White at node 1) 1 (1 Red at node 2) 2 × 1 = 2
Thus, the XOR of all values: 2 XOR 1 XOR 2 = 1.
Example 2:
Input: n = 3, parent = [-1,0,1], gates = [[0,1,2],[1,0,1],[0,0,3]], queries = [[2,0,1,0],[2,1,0,0],[1,1,2,1]]
Output: 3
Explanation:
i Alice [Node, Card] Bob [Node, Card] LCA Alice Path Bob Path Alice Ways Bob Ways Total Ways
0 [2, 0]: Blue [1, 0]: Blue 1 2 → 1 1 3 (3 White at node 2) 1 (no move) 3 × 1 = 3
1 [2, 1]: Red [0, 0]: Blue 0 2 → 1 → 0 0 3 (3 White at node 2) × 1 (1 White at node 1) = 3 1 (no move) 3 × 1 = 3
2 [1, 1]: Red [2, 1]: Red 1 1 2 → 1 1 (no move) 3 (3 White at node 2) 1 × 3 = 3
Thus, the XOR of all values: 3 XOR 3 XOR 3 = 3.
Constraints:
2 <= n <= 2 * 10^4n == parent.length == gates.lengthparent[0] == -10 <= parent[i] < nforiin[1, n - 1]gates[i] == [red_i, blue_i, white_i]0 <= red_i, blue_i, white_i <= 101 <= queries.length <= 2 * 10^4queries[i] = [aNode_i, aCard_i, bNode_i, bCard_i]0 <= aNode_i, bNode_i <= n - 10 <= aCard_i, bCard_i <= 1- The input is generated such that the array
parentrepresents a valid tree.
Solution
Approach: Binary Lifting with 2x2 Matrices
Look at what one climb step does. A person at node v holding a card must use one gate of v to move up. With a blue card (0) there are blue ways to stay blue and white ways to turn red. With a red card (1) there are red ways to stay red and white ways to turn blue. This is a 2x2 matrix over the two card colors:
[[blue, white], [white, red]]
The number of ways to climb a path is the sum of the entries of the row for the starting card in the product of these matrices over the nodes of the path, taken in climbing order. Matrix multiplication is associative, so we can precompute the product over 2j consecutive nodes for every node v and every j, together with the ancestor reached after those nodes. This is the usual binary lifting table, with matrices as values. Entries are kept modulo 109 + 7.
To answer a query:
- Find the LCA with the same table: lift the deeper node to the depth of the other one, then lift both while their ancestors differ.
- For each person, climb
depth[node] - depth[lca]steps by jumping over the set bits of that number, multiplying a vector of two counts (one per card color) by the matrix of each jump. A person who is already at the LCA has exactly 1 way. - The answer for the query is the product of both counts. The final result is the XOR of all query answers.
Note that parents may have larger labels than their children, so depths are found by walking down from the root.
Complexity: O((n + q) log n) time and O(n log n) space, where q is the number of queries.
class Solution:
def distinctPaths(self, n: int, parent: List[int], gates: List[List[int]], queries: List[List[int]]) -> int:
MOD = 10**9 + 7
LOG = max(1, n.bit_length())
# depth of every node (parents may have larger labels than their children, so go top-down)
children = [[] for _ in range(n)]
for v in range(1, n):
children[parent[v]].append(v)
depth = [0] * n
order = [0]
for v in order:
for c in children[v]:
depth[c] = depth[v] + 1
order.append(c)
# Cards: 0 = blue, 1 = red. Leaving node v changes the card according to the 2x2 matrix
# [[blue, white], [white, red]], so the ways to climb a path are a product of such matrices.
# up[j][v] is the product for the 2^j nodes v, parent(v), ... and anc[j][v] the node after them.
anc = [[-1] * n for _ in range(LOG)]
mat = [[None] * n for _ in range(LOG)]
for v in range(n):
red, blue, white = gates[v]
anc[0][v] = parent[v]
mat[0][v] = (blue, white, white, red)
for j in range(1, LOG):
for v in range(n):
mid = anc[j - 1][v]
if mid == -1 or mat[j - 1][mid] is None:
continue
a, b, c, d = mat[j - 1][v]
w = anc[j - 1][mid]
anc[j][v] = w
e, f, g, h = mat[j - 1][mid]
mat[j][v] = ((a * e + b * g) % MOD, (a * f + b * h) % MOD, (c * e + d * g) % MOD, (c * f + d * h) % MOD)
def lift(v: int, steps: int, card: int) -> int:
# number of ways to climb `steps` nodes up from v, starting with the given card
x0, x1 = (0, 1) if card == 1 else (1, 0)
for j in range(LOG):
if steps >> j & 1:
a, b, c, d = mat[j][v]
x0, x1 = (x0 * a + x1 * c) % MOD, (x0 * b + x1 * d) % MOD
v = anc[j][v]
return (x0 + x1) % MOD
ans = 0
for a, ca, b, cb in queries:
# find the LCA
x, y = a, b
if depth[x] < depth[y]:
x, y = y, x
diff = depth[x] - depth[y]
for j in range(LOG):
if diff >> j & 1:
x = anc[j][x]
if x != y:
for j in range(LOG - 1, -1, -1):
if anc[j][x] != anc[j][y]:
x, y = anc[j][x], anc[j][y]
x = anc[0][x]
lca = x
ans ^= lift(a, depth[a] - depth[lca], ca) * lift(b, depth[b] - depth[lca], cb) % MOD
return ans