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 value 2 * val and right child has value 2 * val + 1

You'll process multiple queries where each query [a, b] asks you to:

  1. Add an edge between nodes a and b
  2. Find the cycle length created by this new edge
  3. 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
1234567New Edge (Query: 5โ†”6)Cycle Formation:Path: 5โ†’2โ†’1โ†’3โ†’6 + new edge 6โ†’5Length: 2 steps (5โ†’1) + 2 steps (6โ†’1) + 1 edge = 5๐ŸŽฏ Key: LCA of 5 and 6 is node 1
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.
Asked in
Google 45 Meta 38 Amazon 32 Microsoft 28
47.8K Views
Medium Frequency
~25 min Avg. Time
1.4K 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