Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Implement Breadth-First Search

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Implement Breadth-First Search. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Northern Arizona University's campus navigation service represents locations as a graph. Each location is a node, and each directed edge identifies a directly reachable neighboring location.

Implement bfs_traversal to return the nodes reachable from start in breadth-first search order. When a node has multiple neighbors, process them in the order given by its adjacency list. Mark nodes visited when they are added to the queue so each node is processed at most once.

Formal Specification

Input consists of:

  • graph, a dictionary mapping string node names to lists of neighboring node names.
  • start, a string identifying a node in graph.

Return a list of strings containing every node reachable from start, ordered by BFS traversal. The graph may contain cycles and may be disconnected. Nodes in disconnected components must not appear in the result.

Constraints

  • 1 <= number of nodes <= 10^5
  • 0 <= number of directed edges <= 2 * 10^5
  • Node names are non-empty strings
  • start is a key in graph
  • Every listed neighbor is a key in graph

Function Signature

def bfs_traversal(graph, start):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output