Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
BFS Implementation
00:00
5 left

BFS Implementation

EasyPython

Problem

The Nio Robotics navigation stack represents reachable rover locations as a directed graph. Given an adjacency-list graph and a starting location, implement breadth-first search (BFS) and return the order in which locations are visited.

Visit each reachable location at most once. When processing a location, examine its neighbors in the order listed in the adjacency list. If multiple locations are discovered at the same BFS distance, preserve the discovery order created by that neighbor ordering. Ignore locations that are not reachable from start.

Formal Specification

Implement bfs_traversal(graph, start).

  • graph is a dictionary mapping a node identifier to a list of neighboring node identifiers.
  • start is a node identifier present in graph.
  • Return a list containing the BFS visitation order.
  • The graph may contain cycles and self-loops.
  • The graph is directed. An edge exists from node u to every node in graph[u].

Constraints

  • 1 <= number of nodes <= 10^5
  • 0 <= number of edges <= 2 * 10^5
  • Node identifiers are hashable and unique
  • Every neighbor identifier appears as a key in graph
  • The graph may contain cycles, self-loops, and disconnected components

Function Signature

def bfs_traversal(graph, start):
Interviewer

Your question is BFS Implementation. Start with the requirements in the Question tab.

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.
CodePython 3
You need to log in / sign up to run or submit.Ln 2
Run your code to see test output here.