Graphs · Coding problem
DFS Traversal of Graph
A free coding problem from the Graph BFS/DFS skill. Read it here, then solve it in the app in Java or Python.
- Easy
- Coding problem
- Free
- Java and Python
The problem
Given an undirected graph with n nodes (labeled 0 to n-1) and a list of edges, return the DFS traversal order, visiting each node's neighbors in ascending order and starting a new traversal from the smallest unvisited node whenever the graph is disconnected.
Input format
n m
<m edges, one per line, as "u v">
Example
Input:
5 4
0 1
0 2
1 3
2 4
Output: 0 1 3 2 4
Constraints
1 <= n <= 10^40 <= m <= 2 * 10^4
How it's graded
- Run checks your code against the examples. Submit also runs a hidden suite in four groups - basic cases, edge cases, random inputs and performance tests at the size limit - and shows which groups pass, never the hidden inputs.
- Stuck? Hints come in four steps, from a nudge to a code skeleton, each costing part of the points.
- Once you pass, you see the approaches from brute force to optimal, and where your solution lands among them.
More problems in Graph BFS/DFS
Solve it DFS Traversal of Graph free
No card needed. Lessons, practice questions and easy problems are free forever.
Free plan, no card · 7-day Pro trial · Cancel anytime