Cycle Length Queries in a Tree - Problem
You are given an integer n representing the height of a complete binary tree with 2n - 1 nodes. This tree has a special property:
- The root node has value
1 - For any node with value
val, its left child has value2 * valand right child has value2 * val + 1
You'll process multiple queries where each query [a, b] asks you to:
- Add an edge between nodes
aandb - Find the cycle length created by this new edge
- Remove the edge (queries are independent)
The cycle length is the number of edges in the path that starts and ends at the same node, visiting each edge exactly once.
Your task is to return an array where each element represents the cycle length for the corresponding query.
Input & Output
example_1.py โ Basic Tree Queries
$
Input:
n = 3, queries = [[5,3],[4,7],[2,3]]
โบ
Output:
[4,5,3]
๐ก Note:
For query [5,3]: Path 5โ2โ1โ3 plus new edge 5-3 creates cycle of length 4. For query [4,7]: LCA of 4 and 7 is 1, creating cycle length 5. For query [2,3]: LCA of 2 and 3 is 1, creating cycle length 3.
example_2.py โ Small Tree
$
Input:
n = 2, queries = [[4,5]]
โบ
Output:
[3]
๐ก Note:
Tree has nodes 1,2,3. Nodes 4 and 5 are children of node 2. Their LCA is 2, so cycle length is 1 + 1 + 1 = 3.
example_3.py โ Same Subtree
$
Input:
n = 4, queries = [[8,9]]
โบ
Output:
[3]
๐ก Note:
Nodes 8 and 9 are siblings (both children of node 4). Their LCA is 4, so each node takes 1 step to reach LCA. Cycle length = 1 + 1 + 1 = 3.
Constraints
- 2 โค n โค 30
- 1 โค queries.length โค 105
- 1 โค ai, bi โค 2n - 1
- ai โ bi
Visualization
Tap to expand
Understanding the Visualization
1
Identify Nodes
Start with the two nodes that will be connected by the new edge
2
Find LCA
Move both nodes toward root until they meet at lowest common ancestor
3
Count Steps
Sum the steps each node took to reach the LCA
4
Add Edge
The cycle length is total steps + 1 (for the new edge)
Key Takeaway
๐ฏ Key Insight: In a complete binary tree with this numbering scheme, finding the LCA is extremely efficient because parent relationships follow a simple pattern: parent of node n is n//2.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code