DOM Challenge - #1

Shweta Kale - Feb 17 - - Dev Community

I'm planning to write around 30 posts covering various questions related to DOM traversal, manipulation, and optimization.

Today's question is related to DOM traversal

Question:
Find the common ancestor of two given DOM elements.

In this question we have DOM tree and we need to find common ancestor of given nodes. The first approach I can think of is collect all parent nodes of both elements and find the first common node.

We can get parentNodes using this method

const parentList = (element)=>{
    let el = element;
   const list = [];
    while(true){
        list.push(el);

        if(!el.parentNode) break;
        el = el.parentNode;
    }

    return list;
}
Enter fullscreen mode Exit fullscreen mode

Now we can use this list to find LCA -


const findLCA = (el1, el2)=>{
    const parentList1 = parentList(el1);
    const parentList2 = parentList(el2);

    for(let i=0; i<parentList1.length; i++){
     if(parentList2.includes(parentList1[i])){
         return parentList1[i];
     } 
    }
    return null;
}

Enter fullscreen mode Exit fullscreen mode

This solution works, but it has a time complexity of O(n²) due to the includes() check inside the loop.

We can improve this by using Set to store parent list, so that we can use parentList2.has(parentList1[i]), this is of O(1) complexity so time complexity for our code will be O(n).

💡 Note: These posts are primarily for my learning and practice. They are not meant as official guides but might be helpful for someone preparing for interviews.

. . . . . . . . . . . . . . .