Quick actions

cmd+k|ctrl+k

Navigation

Languages

graphs-general

Snippet info

Language

JavaScript

Visibility

public

Author

ralletsfix

Created

2025-06-25T02:06:32.891089Z

Updated

2025-06-25T02:22:17.995748Z


const graph = [
 [1],
 [0, 2, 4, 5],
 [1, 4, 5],
 [],
 [5, 2, 1],
 [1, 2, 4],
];

function validateAdjacencyList(graph) {
   const nodesCount = graph.length;
   
   for (let node = 0; node < nodesCount; node++) {
       const seen = new Set();
       for (const nbr of graph[node]) {
           // Every node is between 0 and V - 1.
           if (nbr < 0 || nbr >= nodesCount) return false;
           
           // There are no self-loops.
           if (node === nbr) return false;
           
           // There are no parallel edges.
           if (seen.has(nbr)) return false;
           
           seen.add(nbr);
       }
   }
   
   // If node1 appears in graph[node2], then node2 also appears in graph[node1].
   const edges = new Set();
   for (let node1 = 0; node1 < nodesCount; node1++) {
       for (const node2 of graph[node1]) {
           const edge = `[${Math.min(node1, node2)}, ${Math.max(node1, node2)}]`;
           if (edges.has(edge)) edges.delete(edge);
           else edges.add(edge);
       }
   }
   
   return edges.size === 0; 
}

const verdict = validateAdjacencyList(graph);
console.log(verdict);
INFO