Number of Nodes With Value One - Problem

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 label 3 has the node with the label floor(3 / 2) = 1 as its parent, and the node with the label 7 has the node with the label floor(7 / 2) = 3 as 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 0 becomes 1 and vice versa.
  • floor(x) is equivalent to rounding x down to the nearest integer.

Input & Output

Example 1 — Basic Tree
$ Input: n = 7, queries = [2,3,1]
Output: 4
💡 Note: Tree structure: 1 as root, 2,3 as children of 1, 4,5 as children of 2, 6,7 as children of 3. Query 2 flips subtree [2,4,5], query 3 flips subtree [3,6,7], query 1 flips entire tree. Final values: node 1=1, 2=0, 3=0, 4=1, 5=1, 6=1, 7=1. Count = 4.
Example 2 — Single Query
$ Input: n = 3, queries = [2]
Output: 2
💡 Note: Tree: 1 as root, 2,3 as children. Query 2 flips subtree [2]. Final values: node 1=0, 2=1, 3=0. Only nodes 2 has value 1. Count = 1.
Example 3 — Multiple Flips
$ Input: n = 4, queries = [1,1,2]
Output: 2
💡 Note: Tree: 1 as root, 2,3 as children of 1, 4 as child of 2. Query 1 flips all nodes, query 1 again flips all nodes back, query 2 flips subtree [2,4]. Final values: node 1=0, 2=1, 3=0, 4=1. Count = 2.

Constraints

  • 1 ≤ n ≤ 105
  • 1 ≤ queries.length ≤ 105
  • 1 ≤ queries[i] ≤ n

Visualization

Tap to expand
Tree Structure and Query Effects (n=7, queries=[2,3,1])1234567After queries [2,3,1]: Blue=0, Red=0, Green=1Result: 4 nodes with value 1
Understanding the Visualization
1
Tree Structure
Binary tree with parent-child relationships
2
Query Processing
Each query flips entire subtree
3
Final Count
Count nodes with value 1
Key Takeaway
🎯 Key Insight: Count flips per node by checking ancestors instead of simulating each operation
Asked in
Google 25 Microsoft 20 Amazon 15
28.0K Views
Medium Frequency
~25 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen