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:
- Add an edge between the nodes with values
aiandbi. - Find the length of the cycle in the graph.
- Remove the added edge between nodes with values
aiandbi.
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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code