Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

BFS or DFS Traversal

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

Your question is BFS or DFS Traversal. 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

Gartner Peer Insights models related products and categories as a graph. Given an adjacency-list representation, a starting node, and a traversal method, return the nodes reachable from the start in traversal order.

Implement both methods:

  1. BFS: Visit nodes level by level using a queue.
  2. DFS: Visit each available neighbor as deeply as possible using an explicit stack.

When multiple neighbors are available, process them in the order listed in the adjacency list. For iterative DFS, add neighbors to the stack in reverse order so the first listed neighbor is visited first. Each node must appear at most once, even when cycles or multiple paths exist.

Formal Specification

Implement graph_traversal(graph, start, method), where graph is a dictionary mapping node names to lists of neighboring node names, start is a node in the graph, and method is either "bfs" or "dfs". Return a list of node names in the requested traversal order.

Constraints

  • 1 <= number of nodes <= 10^4
  • 0 <= number of edges <= 5 * 10^4
  • Node names are unique non-empty strings
  • The graph may contain cycles and disconnected components
  • start is present in graph
  • method is either "bfs" or "dfs"

Function Signature

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