Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to add the starting node to the queue in BFS.
DSA Python
queue = [] visited = set() start_node = 0 queue.[1](start_node) visited.add(start_node)
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop instead of append will remove an element instead of adding.
Using remove will cause an error if the element is not in the list.
✗ Incorrect
We use append() to add the start_node to the end of the queue for BFS.
2fill in blank
mediumComplete the code to dequeue the first element from the queue in BFS.
DSA Python
current = queue.[1](0)
Attempts:
3 left
💡 Hint
Common Mistakes
Using append will add an element instead of removing.
Using remove without argument causes error.
✗ Incorrect
pop(0) removes and returns the first element from the queue, which is needed for BFS.
3fill in blank
hardFix the error in the BFS loop to check if a neighbor is not visited before adding.
DSA Python
for neighbor in graph[current]: if neighbor not in [1]: queue.append(neighbor) visited.add(neighbor)
Attempts:
3 left
💡 Hint
Common Mistakes
Checking in queue instead of visited can cause duplicates.
Checking in graph or current is incorrect.
✗ Incorrect
We check if neighbor is not in visited set before adding to queue to avoid revisiting nodes.
4fill in blank
hardFill both blanks to complete the function that finds connected components using BFS.
DSA Python
def connected_components(graph): visited = set() components = [] for node in graph: if node not in [1]: component = [] queue = [node] visited.add(node) while queue: current = queue.pop(0) component.append(current) for neighbor in graph[current]: if neighbor not in [2]: queue.append(neighbor) visited.add(neighbor) components.append(component) return components
Attempts:
3 left
💡 Hint
Common Mistakes
Using queue or graph instead of visited causes logic errors.
Using components in condition is incorrect.
✗ Incorrect
We check if node and neighbor are not in visited set to avoid revisiting nodes.
5fill in blank
hardFill all three blanks to create a dictionary comprehension that maps each node to its component index.
DSA Python
def map_nodes_to_components(components): return {node: [1] for idx, comp in enumerate(components) for node in [2] if node not in [3]
Attempts:
3 left
💡 Hint
Common Mistakes
Using components instead of comp causes errors.
Not checking visited causes duplicate keys.
✗ Incorrect
We assign each node the index idx of its component comp, skipping nodes already in visited to avoid duplicates.
