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
from collections import deque def bfs(graph, start): visited = set() queue = deque() queue.[1](start) visited.add(start) while queue: node = queue.popleft() print(node, end=' ') for neighbor in graph[node]: if neighbor not in visited: visited.add(neighbor) queue.append(neighbor) # Example graph graph = { 'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'], 'D': [], 'E': ['F'], 'F': [] } bfs(graph, 'A')
Attempts:
3 left
💡 Hint
Common Mistakes
Using appendleft() instead of append()
Using non-existent methods like push or enqueue
✗ Incorrect
In BFS, we add the starting node to the queue using the append() method of deque.
2fill in blank
mediumComplete the code to check if a neighbor node has been visited before adding it to the queue.
DSA Python
for neighbor in graph[node]: if neighbor [1] visited: visited.add(neighbor) queue.append(neighbor)
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'in' instead of 'not in' causing revisits
Using equality operators instead of membership checks
✗ Incorrect
We only add neighbors that are not yet visited, so we check 'if neighbor not in visited'.
3fill in blank
hardFix the error in the BFS loop to correctly remove the first element from the queue.
DSA Python
while queue: node = queue.[1]() print(node, end=' ') for neighbor in graph[node]: if neighbor not in visited: visited.add(neighbor) queue.append(neighbor)
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() removes from the right end, causing DFS behavior
Using remove() which removes by value, not position
✗ Incorrect
popleft() removes the first element from the deque, which is needed for BFS.
4fill in blank
hardFill both blanks to create a dictionary comprehension that maps each node to its distance from the start node in BFS.
DSA Python
def bfs_distances(graph, start): distances = {start: 0} queue = deque([start]) while queue: node = queue.popleft() for neighbor in graph[node]: if neighbor not in distances: distances[neighbor] = distances[node] [1] 1 queue.[2](neighbor) return distances
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-' instead of '+' for distance calculation
Using appendleft() which changes BFS order
✗ Incorrect
We add 1 to the current node's distance and append the neighbor to the queue.
5fill in blank
hardFill all three blanks to create a BFS function that returns the order of nodes visited as a list.
DSA Python
def bfs_order(graph, start): visited = set([start]) queue = deque([start]) order = [] while queue: node = queue.[1]() order.[2](node) for neighbor in graph[node]: if neighbor not in visited: visited.add(neighbor) queue.[3](neighbor) return order
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() instead of popleft() changes traversal order
Using appendleft() to enqueue neighbors reverses BFS order
✗ Incorrect
Use popleft() to dequeue, append() to add to order list and to enqueue neighbors.
