DFS Traversal - Problem

Implement depth-first search (DFS) traversal for a graph using both iterative (stack-based) and recursive approaches.

Given an adjacency list representation of an undirected graph and a starting vertex, return a list of vertices visited in DFS order. If multiple neighbors exist, visit them in ascending numerical order.

Requirements:

  • Implement both iterative and recursive versions
  • Return vertices in the order they are first visited
  • Handle disconnected components (only traverse from the given start vertex)
  • Visit neighbors in ascending order for consistent output

Input & Output

Example 1 — Connected Graph
$ Input: graph = {"0": [1, 2], "1": [0, 3, 4], "2": [0, 5], "3": [1], "4": [1], "5": [2]}, start = 0
Output: [0,1,3,4,2,5]
💡 Note: Starting from node 0, visit neighbors 1 and 2. From node 1, visit neighbors 3 and 4. From node 2, visit neighbor 5. All nodes are reachable.
Example 2 — Partial Graph
$ Input: graph = {"0": [1], "1": [0, 2], "2": [1], "3": [4], "4": [3]}, start = 0
Output: [0,1,2]
💡 Note: Starting from node 0, can only reach nodes 1 and 2. Nodes 3 and 4 form a separate component and are not reachable from 0.
Example 3 — Single Node
$ Input: graph = {"0": []}, start = 0
Output: [0]
💡 Note: Single isolated node with no neighbors. DFS returns just the starting node.

Constraints

  • 1 ≤ number of nodes ≤ 1000
  • 0 ≤ number of edges ≤ 2000
  • Graph is represented as adjacency list with string keys
  • All node values are non-negative integers

Visualization

Tap to expand
DFS Traversal Problem OverviewINPUT GRAPH012345Adjacency List:0: [1, 2]1: [0, 3, 4]2: [0, 5]Start: Node 0DFS ALGORITHM1Visit node 0, mark visited2Explore neighbors [1, 2]3Go deep: 0→1→3, then 1→44Backtrack to 0, visit 2→5Stack/RecursionLast In, First OutGo deep then backtrackTime: O(V + E)Space: O(V)RESULTTraversal Order[0, 1, 3, 4, 2, 5]Visit order:0 → 1 → 3 → 4 → 2 → 5Depth-first explorationvisits each node onceAll nodes visited!Connected componentfrom starting nodeKey Insight:DFS goes as deep as possible before backtracking, using stack (LIFO) behavior to systematically explore every reachable node exactly once.TutorialsPoint - DFS Traversal | Graph Algorithms
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
28.5K Views
High Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen