Walk the graph breadth first and join the nodes visited.
Acceptance criteria
- 1.#out should show a-b-c-d.
DSA Tutorial · Graphs
These 10 tasks go with the Graph Traversal: BFS and DFS chapter. 5 of them ask you to build something small from scratch; 5 give you code that is already broken and ask you to work out why. Set aside about 90 minutes for the whole set, though you can do them in any order.
Nothing here is marked by a person. When you press Submit, the editor checks your code against the points listed under each task and tells you straight away what passed and what didn't (you need a free account to submit). If you get stuck, there are hints, and a worked solution once you've had a go. The first 2 tasks are free; the rest are part of the practice plan.
If it's been a while since you read the chapter, here is how it starts: “BFS and DFS differ by one thing: a queue or a stack. Everything else is identical, including the visited set you cannot leave out.” .
1.Breadth first orderexercise · easy · 10 min
Walk the graph breadth first and join the nodes visited.
Passes when: #out should show a-b-c-d.
2.Depth first orderexercise · easy · 10 min · practice plan
Walk depth first with recursion and join the nodes visited.
Passes when: #out should show a-b-d-c.
3.Count the reachableexercise · easy · 10 min · practice plan
Count how many nodes can be reached from a.
Passes when: #out should show four reachable.
4.Shortest hop countexercise · easy · 10 min · practice plan
Report the fewest edges from a to d.
Passes when: #out should show hops 2.
5.Unreachable nodeexercise · medium · 10 min · practice plan
Report that an isolated node cannot be reached.
Passes when: #out should show unreachable.
6.Fix the traversal without a visited setbug fix · easy · 8 min
Revisiting nodes repeats them, so a guard caps the walk here.
Passes when: #out should show visited 3.
7.Fix BFS using a stackbug fix · medium · 8 min · practice plan
Popping from the back makes the walk depth first, so the order changes.
Passes when: #out should show a-b-c-d.
8.Fix the node marked after dequeuebug fix · easy · 8 min · practice plan
Marking on removal lets a node be queued twice before it is seen.
Passes when: #out should show four reachable.
9.Fix the distance overwrittenbug fix · easy · 8 min · practice plan
Updating a distance already set replaces the shortest with a longer one.
Passes when: #out should show hops 2.
10.Fix the isolated node countedbug fix · easy · 8 min · practice plan
A node present in the map is not necessarily reachable.
Passes when: #out should show unreachable.
Between them these tasks cover Visited sets, Queue vs stack and Shortest hops.
Looking for a different chapter? See every practice set, or switch to the interview theory questions.