#2509
Cycle Length Queries in a Tree
HardArrayTreeBinary TreeLowest Common Ancestor (LCA)Binary Tree Properties
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages the properties of binary trees and the concept of the Lowest Common Ancestor (LCA) to efficiently calculate the cycle length without constructing the tree explicitly.
⚙️
Algorithm
3 steps- 1Step 1: For each query, find the depth of nodes a and b.
- 2Step 2: Find the Lowest Common Ancestor (LCA) of nodes a and b.
- 3Step 3: Calculate the cycle length using the formula: cycle_length = depth(a) + depth(b) - 2 * depth(LCA(a, b)) + 2.
solution.py21 lines
1class Solution:
2 def cycleLengthQueries(self, n, queries):
3 def depth(x):
4 return (x).bit_length() - 1
5 def lca(a, b):
6 while a != b:
7 if a > b:
8 a //= 2
9 else:
10 b //= 2
11 return a
12 results = []
13 for a, b in queries:
14 d_a = depth(a)
15 d_b = depth(b)
16 lca_node = lca(a, b)
17 d_lca = depth(lca_node)
18 cycle_length = d_a + d_b - 2 * d_lca + 2
19 results.append(cycle_length)
20 return results
21ℹ
Complexity note: The optimal solution runs in O(n) time for each query due to the logarithmic depth calculations and the LCA finding process, making it efficient for larger trees.
- 1Understanding the properties of binary trees helps in efficiently finding the cycle length.
- 2The Lowest Common Ancestor (LCA) is crucial for calculating distances in trees.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.