Cycle Length Queries in a Tree - Lowest Common Ancestor [JS]

Description 

Solution: Lowest Common Ancestor

For each [a, b] in queries,

  • Find the distance between node a and b.
  • To find the distance between node a and b, 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 > ba is on a deeper level than b (because all nodes at level x will be smaller than nodes at level x + 1).
  • If a > b, move a up to the parent node. Otherwise move b up to the parent node.
  • To find the parent node: Math.floor(x / 2)
  • Traverse to the parents of each node until both a and b 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 queriesn = 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

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]