Complete the code to check if a graph has cycles.
function hasCycle(graph) {
const visited = new Set();
function dfs(node, parent) {
visited.add(node);
for (const neighbor of graph[node]) {
if (!visited.has(neighbor)) {
if (dfs(neighbor, node)) return true;
} else if (neighbor !== [1]) {
return true;
}
}
return false;
}
for (const node in graph) {
if (!visited.has(node)) {
if (dfs(node, null)) return true;
}
}
return false;
}The cycle check compares the neighbor with the parent node to avoid false positives.
Complete the code to add an edge in an undirected graph.
function addEdge(graph, u, v) {
if (!graph[u]) graph[u] = [];
if (!graph[v]) graph[v] = [];
graph[u].push(v);
graph[v].[1](u);
}append which is not valid in JavaScript arrays.add which is for sets, not arrays.Use push to add an element to the array representing adjacency.
Fix the error in the code to check if a tree is a valid tree (no cycles and connected).
function isValidTree(n, edges) {
const graph = {};
for (const [u, v] of edges) {
if (!graph[u]) graph[u] = [];
if (!graph[v]) graph[v] = [];
graph[u].push(v);
graph[v].push(u);
}
for(let i = 0; i < n; i++) {
if (!graph[i]) graph[i] = [];
}
const visited = new Set();
function dfs(node, parent) {
visited.add(node);
for (const neighbor of graph[node]) {
if (!visited.has(neighbor)) {
if (dfs(neighbor, node)) return true;
} else if (neighbor !== [1]) {
return true;
}
}
return false;
}
if (dfs(0, -1)) return false;
return visited.size === n;
}The cycle detection must ignore the parent node to avoid false positives.
Complete the code to create an object that maps words to their lengths only if length is greater than 3.
const words = ['tree', 'graph', 'node', 'edge']; const result = {}; for (const word of words) { if (word.length > 3) { result[[1]] = [2]; } }
The key is the word itself, and the value is its length.
Fill in the blanks to create a filtered object of uppercase keys and their lengths for words longer than 4 characters.
const words = ['tree', 'graph', 'node', 'edge', 'vertex']; const filtered = {}; for (const word of words) { if (word.length [3] 4) { filtered[[1]] = [2]; } }
Keys are uppercase words, values are lengths, filtered by length greater than 4.
