High interview relevanceRoadmap: Intermediate
TimeO(V + E)
SpaceO(V)

Why it costs this much

Each vertex is entered once, and each edge is examined once.

Code

def dfs(graph, u, seen):
    seen.add(u)
    for v in graph[u]:              # each edge is examined once overall
        if v not in seen:
            dfs(graph, v, seen)     # each vertex is entered once

Common pitfalls

Recursion depth can reach V, which exceeds Python's default recursion limit (about 1000) on long chains. Use an explicit stack for deep graphs.

Operation by operation

OperationBestAverageWorstSpace
Depth-first searchO(V + E)O(V + E)O(V + E)O(V)

Depth-first search. Adjacency list. Space is the recursion depth plus the visited set. Recursive DFS can overflow the stack on deep graphs. Use an explicit stack.

Keyboard shortcuts

/
Search topics
?
Show this list of shortcuts
r
Open the revision sheet
b
Save or unsave the focused card, or the topic you are reading
l
Mark the focused card, or the topic you are reading, as learned
Space Left arrow Right arrow
In the visualizer: play or pause, step back, step forward
1 to 4 Enter
In the quiz: pick an answer, then go to the next question
Escape
Close this list