Cycle Length Queries in a Tree - Problem

You are given an integer n. There is a complete binary tree with 2^n - 1 nodes. The root of that tree is the node with the value 1, and every node with a value val in the range [1, 2^(n-1) - 1] has two children where:

  • The left node has the value 2 * val, and
  • The right node has the value 2 * val + 1.

You are also given a 2D integer array queries of length m, where queries[i] = [ai, bi]. For each query, solve the following problem:

  1. Add an edge between the nodes with values ai and bi.
  2. Find the length of the cycle in the graph.
  3. Remove the added edge between nodes with values ai and bi.

Note that:

  • A cycle is a path that starts and ends at the same node, and each edge in the path is visited only once.
  • The length of a cycle is the number of edges visited in the cycle.
  • There could be multiple edges between two nodes in the tree after adding the edge of the query.

Return an array answer of length m where answer[i] is the answer to the ith query.

Input & Output

Example 1 — Basic Tree Query
$ Input: n = 3, queries = [[4,5],[5,3],[2,3]]
Output: [5,4,3]
💡 Note: For query [4,5]: LCA is 1, distances are 2+2+1=5. For [5,3]: LCA is 1, distances are 2+1+1=4. For [2,3]: LCA is 1, distances are 1+1+1=3.
Example 2 — Smaller Tree
$ Input: n = 2, queries = [[2,3]]
Output: [3]
💡 Note: Tree has nodes 1,2,3. LCA(2,3) = 1. Distance(2→1) = 1, Distance(3→1) = 1. Cycle length = 1+1+1 = 3.
Example 3 — Same Subtree
$ Input: n = 4, queries = [[4,5]]
Output: [3]
💡 Note: Nodes 4 and 5 have LCA = 2. Distance(4→2) = 1, Distance(5→2) = 1. Cycle length = 1+1+1 = 3.

Constraints

  • 2 ≤ n ≤ 20
  • 1 ≤ queries.length ≤ 105
  • 1 ≤ ai, bi ≤ 2n - 1

Visualization

Tap to expand
Cycle Length Queries in Complete Binary Tree1234567Query: [4,5]Query [4,5]: Add edge 4↔5Cycle: 4→2→1→2→5→4LCA(4,5) = 2, dist(4→2)=1, dist(5→2)=1Inputn = 3queries = [[4,5],[5,3],[2,3]]Output[5,4,3]
Understanding the Visualization
1
Input
Complete binary tree with n=3 (7 nodes) and queries
2
Process
Add edge temporarily and find cycle length
3
Output
Array of cycle lengths for each query
Key Takeaway
🎯 Key Insight: When adding an edge between nodes a and b in a tree, the cycle length is distance(a,LCA) + distance(b,LCA) + 1
Asked in
Google 25 Microsoft 18 Amazon 15
8.9K Views
Medium Frequency
~25 min Avg. Time
342 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