Number of Nodes With Value One Problem
Description
LeetCode Problem 2445.
There is an undirected connected tree with n nodes labeled from 1 to n and n - 1 edges. You are given the integer n. The parent node of a node with a label v is the node with the label floor (v / 2). The root of the tree is the node with the label 1.
- For example, if
n = 7, then the node with the label3has the node with the labelfloor(3 / 2) = 1as its parent, and the node with the label7has the node with the labelfloor(7 / 2) = 3as its parent.
You are also given an integer array queries. Initially, every node has a value 0 on it. For each query queries[i], you should flip all values in the subtree of the node with the label queries[i].
Return the total number of nodes with the value 1 after processing all the queries.
Note that:
- Flipping the value of a node means that the node with the value
0becomes1and vice versa. floor(x)is equivalent to roundingxdown to the nearest integer.
Example 1:

Input: n = 5 , queries = [1,2,5]
Output: 3
Explanation: The diagram above shows the tree structure and its status after performing the queries. The blue node represents the value 0, and the red node represents the value 1.
After processing the queries, there are three red nodes (nodes with value 1): 1, 3, and 5.
Example 2:

Input: n = 3, queries = [2,3,3]
Output: 1
Explanation: The diagram above shows the tree structure and its status after performing the queries. The blue node represents the value 0, and the red node represents the value 1.
After processing the queries, there are one red node (node with value 1): 2.
Constraints:
1 <= n <= 10^51 <= queries.length <= 10^51 <= queries[i] <= n
Solution
Approach: Simulation with Flip Parities
Flipping a node's subtree twice changes nothing, so only the parity of the number of queries at each node matters. Record that parity per node. Then walk the nodes from the root down: a node's flip state is its parent's state XOR its own query parity (the parent of node i is i / 2). A node ends with value 1 exactly when its state is 1, so we count those.
Complexity: O(n + q) time and O(n) space, where n is the number of nodes and q the number of queries.
class Solution:
def numberOfNodes(self, n: int, queries: List[int]) -> int:
def dfs(i):
if i > n:
return
tree[i] ^= 1
dfs(i << 1)
dfs(i << 1 | 1)
tree = [0] * (n + 1)
cnt = Counter(queries)
for i, v in cnt.items():
if v & 1:
dfs(i)
return sum(tree)