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
a
andb
. - To find the distance between node
a
andb
, 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
,a
is on a deeper level thanb
(because all nodes at levelx
will be smaller than nodes at levelx + 1
). - If
a > b
, movea
up to the parent node. Otherwise moveb
up to the parent node. - To find the parent node:
Math.floor(x / 2)
- Traverse to the parents of each node until both
a
andb
are 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