Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the visited set before BFS.
DSA Typescript
const visited = new Set[1](); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using brackets [] instead of parentheses () to create a Set.
Trying to initialize Set with curly braces {} which is an object literal.
✗ Incorrect
We create a new Set by calling new Set() with parentheses.
2fill in blank
mediumComplete the code to add the starting node to the queue in BFS.
DSA Typescript
queue.push[1](startNode); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using .add which is for Sets, not arrays.
Writing queue.push without parentheses, which is a function reference, not a call.
✗ Incorrect
We call the push method with parentheses and the node as argument: push(startNode).
3fill in blank
hardFix the error in the BFS loop condition to process nodes while queue is not empty.
DSA Typescript
while (queue[1] 0) {
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using == 0 which stops immediately.
Using < 0 which is never true for length.
✗ Incorrect
We check if queue length is greater than 0 to continue processing nodes.
4fill in blank
hardFill both blanks to check if a neighbor is unvisited and add it to the queue.
DSA Typescript
if (!visited.has(neighbor) && !queue[1].includes(neighbor)) { queue[2](neighbor); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop or shift to add elements instead of push.
Checking queue with wrong method instead of includes.
✗ Incorrect
We check if neighbor is not in queue using includes, then add it with push.
5fill in blank
hardFill all three blanks to complete the BFS function that finds connected components.
DSA Typescript
function bfs(graph: Map<string, string[]>): string[][] {
const visited = new Set<string>();
const components: string[][] = [];
for (const node of graph.keys()) {
if (!visited.has(node)) {
const queue = [node];
const component: string[] = [];
while (queue.length [1] 0) {
const current = queue[2]();
if (!visited.has(current)) {
visited.add(current);
component.push(current);
for (const neighbor of graph.get(current) || []) {
if (!visited.has(neighbor)) {
queue.push(neighbor);
}
}
}
}
components.push(component);
}
}
return components;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() removes last element, which is DFS behavior.
Using < 0 or == 0 in loop condition stops loop incorrectly.
✗ Incorrect
We loop while queue length > 0, remove the first element with shift. pop is a distractor here.