Coding Challenge Practice – Question 54



This content originally appeared on DEV Community and was authored by Bukunmi Odugbesan

The task is to return the next sibling, given a DOM tree and a target element.

The boilerplate code

function nextRightSibling(root, target) {
  // your code here
}

If there is no next sibling, return null

If(!root || !target) return null;

Process the DOM tree level by level. Keep track of the level of the target element.

const queue = [[root, 0]];
  let targetDepth = null;

  while (queue.length) {
    const [node, depth] = queue.shift();

    if (node === target) {
      targetDepth = depth;
      continue;
    }

After the target is found, the next element on the same level as the target is the right sibling. If the next element is on a lower depth, the target has no right sibling

if (targetDepth !== null) {
      if (depth === targetDepth) {
        return node;
      } else if (depth > targetDepth) {
        return null;
      }
    }

The final code

function nextRightSibling(root, target) {
  // your code here
  if(!root || !target) return null;

  const queue = [[root, 0]];
  let targetDepth = null;

  while(queue.length) {
    const [node, depth] = queue.shift();

    if(node === target) {
      targetDepth = depth;
      continue;
    } 
    if(targetDepth !== null) {
      if(depth === targetDepth) {
        return node;
      } else if( depth > targetDepth) {
        return null;
      }
    }
    for(let child of node.children) {
      queue.push([child, depth + 1]);
    }
  }
  return null
}

That’s all folks!


This content originally appeared on DEV Community and was authored by Bukunmi Odugbesan