Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the queue with the starting node for BFS.
DSA Javascript
const bfs = (graph, start) => {
const queue = [[1]];
const visited = new Set();
visited.add(start);
while (queue.length > 0) {
const node = queue.shift();
console.log(node);
for (const neighbor of graph[node]) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push(neighbor);
}
}
}
};Attempts:
3 left
💡 Hint
Common Mistakes
Initializing the queue with the entire graph or an empty array.
Forgetting to add the start node to the queue.
✗ Incorrect
The BFS queue must start with the starting node to begin traversal from there.
2fill in blank
mediumComplete the code to check if a neighbor node has been visited before adding it to the queue.
DSA Javascript
for (const neighbor of graph[node]) { if (![1].has(neighbor)) { visited.add(neighbor); queue.push(neighbor); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Checking the queue instead of the visited set.
Checking the graph or node variable incorrectly.
✗ Incorrect
We check the 'visited' set to avoid revisiting nodes and prevent infinite loops.
3fill in blank
hardFix the error in the code to correctly remove the first element from the queue.
DSA Javascript
const node = queue.[1]();Attempts:
3 left
💡 Hint
Common Mistakes
Using 'pop()' which removes the last element, breaking BFS order.
Using 'push()' or 'unshift()' which add elements instead of removing.
✗ Incorrect
In BFS, we remove the first element from the queue using 'shift()' to process nodes in FIFO order.
4fill in blank
hardFill both blanks to add neighbors to the queue and mark them visited during BFS.
DSA Javascript
if (!visited.[1](neighbor)) { visited.[2](neighbor); queue.push(neighbor); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'delete' or 'clear' instead of 'add' to mark visited.
Using 'has' incorrectly as a method to add elements.
✗ Incorrect
We check if 'visited' has the neighbor, then add it to 'visited' before pushing to the queue.
5fill in blank
hardFill all three blanks to create a BFS function that prints nodes in correct order.
DSA Javascript
const bfs = (graph, start) => {
const queue = [[1]];
const visited = new Set();
visited.[2](start);
while (queue.length > 0) {
const node = queue.[3]();
console.log(node);
for (const neighbor of graph[node]) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push(neighbor);
}
}
}
};Attempts:
3 left
💡 Hint
Common Mistakes
Using 'pop()' instead of 'shift()' breaks BFS order.
Forgetting to add start node to visited set.
✗ Incorrect
Start the queue with 'start', add 'start' to visited, and remove nodes from queue with 'shift()' for BFS order.
