Skip to content

Instantly share code, notes, and snippets.

@btsheehy
Created November 18, 2020 18:35
Show Gist options
  • Save btsheehy/3c8ff3ebc44a1b0527ea0db13869eb3d to your computer and use it in GitHub Desktop.
Save btsheehy/3c8ff3ebc44a1b0527ea0db13869eb3d to your computer and use it in GitHub Desktop.
getLowestCommonDenominator challenge
// write a function getLowestCommonAncestor(root, id1, id2)
// it should return the lowest common ancestor
// getLowestCommonAncestor(root, 13, 13) === 13
// getLowestCommonAncestor(root, 14, 14) === 14
// getLowestCommonAncestor(root, 13, 14) === 6
// getLowestCommonAncestor(root, 12, 14) === 2
// getLowestCommonAncestor(root, 7, 14) === 0
const root = {
id: 0,
children: [
{
id: 1,
children: [
{
id: 3,
children: [
{
id: 7,
children: [],
},
{
id: 8,
children: [],
},
],
},
{
id: 4,
children: [
{
id: 9,
children: [],
},
{
id: 10,
children: [],
},
],
},
],
},
{
id: 2,
children: [
{
id: 5,
children: [
{
id: 11,
children: [],
},
{
id: 12,
children: [],
},
],
},
{
id: 6,
children: [
{
id: 13,
children: [],
},
{
id: 14,
children: [],
},
],
},
],
},
],
}
const getPaths = (paths, node, currentPath) => ({
...paths,
[node.id]: currentPath,
...node.children.reduce(
(acc, val) => ({
...acc,
...getPaths(acc, val, [...currentPath, val.id]),
}),
{}
),
})
const getLowestCommonAncestor = (root, id1, id2) => {
const paths = getPaths({}, root, [root.id])
const path1 = paths[id1]
const path2 = paths[id2]
return path1.reverse().find(a => path2.includes(a))
}
console.log([
getLowestCommonAncestor(root, 13, 13) === 13,
getLowestCommonAncestor(root, 14, 14) === 14,
getLowestCommonAncestor(root, 13, 14) === 6,
getLowestCommonAncestor(root, 12, 14) === 2,
getLowestCommonAncestor(root, 7, 14) === 0,
])
// This solution would ideally involve a cache
// of some sort so that `paths` isn't calculated
// on every call
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment