Number of Nodes With Value One

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution:
    def numberOfNodes(self, n: int, queries: List[int]) -> int:

        # Initialize a dictionary to keep track of the flip count for each node
        flipped = {}
        for i in range(n + 1):
            flipped[i] = 0

        # Count flips for each query node and increment flip count
        for query in queries:
            flipped[query] += 1

        # Initialize a variable to keep track of nodes with value 1
        res = 0

        # Iterate through nodes from 1 to n
        for i in range(1, n + 1):
            # Propagate flips to child nodes by adding parent's flip count to current node's flip count
            flipped[i] += flipped[i // 2]

            # Check if the node has been flipped an odd number of times
            if flipped[i] % 2 == 1:
                # Increment the count of nodes with value 1
                res += 1

        # Return the total count of nodes with value 1
        return res