Cycle Length Queries in a Tree - Lowest Common Ancestor [JS]
Solution: Lowest Common Ancestor
For each [a, b] in queries,
- Find the distance between node
aandb. - To find the distance between node
aandb, we need to find the distance of each node from the lowest common ancestor of(a, b). - The length of the cycle =
1 + (distance of node a from LCA) + (distance of node b from LCA).
To find the length of the cycle:
- We know that if
a > b,ais on a deeper level thanb(because all nodes at levelxwill be smaller than nodes at levelx + 1). - If
a > b, moveaup to the parent node. Otherwise movebup to the parent node. - To find the parent node:
Math.floor(x / 2) - Traverse to the parents of each node until both
aandbare equal (find the lowest common ancestor). - Keep track of the number of times we traversed a parent node.
- Return the
count + 1.
m = number of queries, n = height of the tree
Time Complexity: O(mn) 342ms
Space Complexity: O(m) 73.5MB
var cycleLengthQueries = function(n, queries) {
let m = queries.length, ans = Array(m);
for (let i = 0; i < m; i++) {
let [a, b] = queries[i];
ans[i] = findCycleLen(a, b);
}
return ans;
};
function findCycleLen(a, b) {
let len = 0;
while (a !== b) {
if (a > b) {
a = Math.floor(a / 2);
} else {
b = Math.floor(b / 2);
}
len++;
}
return len + 1;
}
Comments
Post a Comment