Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Traverse a Graph With BFS/DFS

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

Your question is Traverse a Graph With BFS/DFS. 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

Box may represent folder relationships, shared links, or shortcuts as a graph rather than a strict tree. Given an adjacency-list representation of this graph, return the folders visited by a breadth-first search starting from a specified folder.

Visit each folder at most once, even when cycles or multiple paths exist. When processing a folder, examine its neighbors in the order provided by the adjacency list. Ignore folders that are not reachable from start.

Formal Specification

Implement traverse_box_graph(graph, start), where graph is a dictionary mapping a folder ID string to a list of directly connected folder ID strings, and start is a folder ID string. Return a list of folder IDs in BFS visitation order. The input graph is unweighted, and every referenced folder appears as a key.

Examples

Example 1

Input: graph = {"A": ["B", "C"], "B": ["D"], "C": ["E"], "D": [], "E": []}, start = "A"

Output: ["A", "B", "C", "D", "E"]

B and C are visited before either of their children because BFS processes one level at a time.

Example 2

Input: graph = {"A": ["B"], "B": ["C", "A"], "C": []}, start = "A"

Output: ["A", "B", "C"]

The visited set prevents the edge from B back to A from causing repeated visits.

Constraints

  • 1 <= number of folders <= 10^5
  • 0 <= number of relationships <= 2 * 10^5
  • Folder IDs are non-empty strings
  • The graph may contain cycles, self-loops, and disconnected components
  • The starting folder exists in graph

Function Signature

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