Search code examples
javascriptdomtime-complexityparent-childspace-complexity

How to find time and space complexity for this js code?


These are two codes that my platform is using to find relationship between two nodes. code1 :

const getNodeRelationship = (node1, node2) => {
    // if node1 and node2 are the same node
    if (node1 === node2) return null;

    // check direct parent
    let parent = node1.parentElement
    if (parent === node2) {
        return 'parent';
    }

    // if both node1 and node2 have the same parent
    if (node1.parentNode === node2.parentNode) {
        return 'sibling';
    }

    // check direct children
    for (const child of node1.children) {
        if (child === node2) return 'child';
    }

    return null;
}

code2:

const getNodeRelationship = (node1, node2) => {
    // Helper function to check the relation between the two nodes
    const checkParentDirectChild = (parent, child) => {
        // If the parent node exists, iterate over its childNodes
        if (parent) {
            for (const curNode of parent.childNodes) {
                if (curNode === child) {
                    return true;
                }
            }
        }
        return false;
    }

    // if node1 and node2 are the same node
    if (node1 === node2) {
        return null;
    }
    
    // if node2 is a direct child of node1
    if (checkParentDirectChild(node1, node2)) {
        return 'child';
    }

    // if node1 is a direct child of node2
    if (checkParentDirectChild(node2, node1)) {
        return 'parent';
    }
    
    // if both node1 and node2 have the same parent
    if (checkParentDirectChild(node1.parentNode, node2) && checkParentDirectChild(node2.parentNode, node1)) {
        return 'sibling';
    }
    
    return null;
}

I think the tc and sc will be O(1) for both the codes as we check for a direct parent-child relationship between two nodes. Since we are not doing any types of DFS or BFS

But If node1 has a million child nodes and node2 is the last of them, wouldn't the for run a million times in the two solutions proposed?

I am confused. Can anyone help me verify about time and space?


Solution

  • But If node1 has a million child nodes and node2 is the last of them, wouldn't the for run a million times in the two solutions proposed?

    Yes, in the worst case it would. That is the reason why you need to know what the branching factor 𝑏 is of your tree. Either average or maximum branching factor will do. And then the time complexity is O(𝑏) because of the loop over the children of either node.

    The space complexity is O(1).