# Youngest Common Ancestor

<figure><img src="/files/gm35PUW3ypPLT07McP7v" alt=""><figcaption></figcaption></figure>

* h, h

```jsx
// This is an input class. Do not edit.
class AncestralTree {
  constructor(name) {
    this.name = name;
    this.ancestor = null;
  }
}

function getYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo) {

  const pathOne = hasBAsAncestor(descendantOne, topAncestor);
  const pathTwo = hasBAsAncestor(descendantTwo, topAncestor);

  let idx1 = pathOne.length - 1;
  let idx2 = pathTwo.length - 1;
  while (idx1 >= 0 && idx2 >= 0) {
    if (pathOne[idx1] !== pathTwo[idx2]) break;
    idx1--;
    idx2--;
  }

  return pathOne[idx1 + 1];
}

function hasBAsAncestor(node) {
  const path = [];
  
  let currentNode = node;
  while (currentNode !== null) {
    path.push(currentNode);  
    currentNode = currentNode.ancestor;
  }

  return path;
}

// Do not edit the lines below.
exports.AncestralTree = AncestralTree;
exports.getYoungestCommonAncestor = getYoungestCommonAncestor;
```

* h, 1

```jsx
// This is an input class. Do not edit.
class AncestralTree {
  constructor(name) {
    this.name = name;
    this.ancestor = null;
  }
}

function getYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo) {
  const d1 = findDepth(descendantOne);
  const d2 = findDepth(descendantTwo);

  let diff = Math.abs(d1 - d2);
  if (d1 > d2) {
    while (diff > 0) {
      descendantOne = descendantOne.ancestor;
      diff--;
    }
  } else if (d1 < d2) {
    while (diff > 0) {
      descendantTwo = descendantTwo.ancestor;
      diff--;
    }  
  }

  while (descendantOne !== descendantTwo) {
    descendantOne = descendantOne.ancestor;
    descendantTwo = descendantTwo.ancestor;
  }

  return descendantOne;
}

function findDepth(node) {
  let depth = 0;
  
  let currentNode = node;
  while (currentNode !== null) {
    depth += 1;
    currentNode = currentNode.ancestor
  }

  return depth - 1;
}

// Do not edit the lines below.
exports.AncestralTree = AncestralTree;
exports.getYoungestCommonAncestor = getYoungestCommonAncestor;
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/algorithm-problems/algoexpert/medium/youngest-common-ancestor.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
