0
0
DSA Typescriptprogramming~10 mins

Connected Components Using BFS in DSA Typescript - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
A<string>
B()
C[]
D{}
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.
2fill in blank
medium

Complete 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'
A.add
B.enqueue
C.push
D()
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.
3fill in blank
hard

Fix 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'
A>
B==
C!==
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using == 0 which stops immediately.
Using < 0 which is never true for length.
4fill in blank
hard

Fill 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'
A.push
B.pop
D.shift
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop or shift to add elements instead of push.
Checking queue with wrong method instead of includes.
5fill in blank
hard

Fill 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'
A>
Bshift
Cpop
D<
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.