Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Depth-First Traversal Order

Graphseasy

Given an adjacency list `adj` and a `start` node, implement `dfs(adj, start)` returning the order nodes are visited by depth-first search, visiting neighbors in listed order.

Sample tests

Input: dfs([[1,2],[0,3],[0,3],[1,2]], 0)
Output: [0,1,3,2]
Input: dfs([[1,2],[],[]], 0)
Output: [0,1,2]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Missing the visited check causes infinite loops on cycles.

Learning resources

  • Wikipedia: Graph traversal
Approach & explanation (try first)

DFS follows each branch to its end before backtracking. O(V + E) time.

Loading...
⌘/Ctrl + Enter

Run your code to see results.