Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to add the starting node to the queue in BFS.
DSA Java
Queue<Integer> queue = new LinkedList<>();
boolean[] visited = new boolean[n];
visited[start] = true;
queue.[1](start);Attempts:
3 left
💡 Hint
Common Mistakes
Using 'push' which is for stacks, not queues.
Using 'enqueue' which is not a Java Queue method.
✗ Incorrect
In Java's Queue interface, 'offer' is the preferred method to add elements to the queue safely.
2fill in blank
mediumComplete the code to dequeue the next node in BFS.
DSA Java
while (!queue.isEmpty()) { int current = queue.[1](); // process current node }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'pop' which is for stacks.
Using 'peek' which does not remove the element.
✗ Incorrect
'poll' removes and returns the head of the queue or returns null if empty, suitable for BFS.
3fill in blank
hardFix the error in the adjacency list traversal to check neighbors in BFS.
DSA Java
for (int neighbor : graph.get(current)) { if (!visited[[1]]) { visited[neighbor] = true; queue.offer(neighbor); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Checking visited[current] inside the loop over neighbors.
Using graph or queue as index which is invalid.
✗ Incorrect
We must check if the neighbor node is visited, not the current node.
4fill in blank
hardFill both blanks to correctly initialize the BFS queue and visited array.
DSA Java
boolean[] visited = new boolean[[1]]; Queue<Integer> queue = new [2]<>();
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'm' which might be edges count for visited array size.
Using ArrayList for queue which is not a Queue implementation.
✗ Incorrect
The visited array size should be the number of nodes 'n'. The queue is best implemented as a LinkedList.
5fill in blank
hardFill all three blanks to complete BFS traversal printing nodes in order.
DSA Java
while (!queue.isEmpty()) { int current = queue.[1](); System.out.print(current + " "); for (int neighbor : graph.get(current)) { if (!visited[neighbor]) { visited[neighbor] = true; queue.[2](neighbor); } } } // Output example: [3]
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'add' instead of 'offer' which works but 'offer' is preferred.
Using 'peek' instead of 'poll' which does not remove the element.
✗ Incorrect
'poll' removes the head of the queue, 'offer' adds neighbors, and the output shows BFS order of nodes.
