Bird
Raised Fist0
DSA Pythonprogramming~20 mins

DFS Depth First Search on Graph in DSA Python - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
DFS Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of DFS traversal on a simple graph
What is the output of the following DFS traversal starting from node 'A'?
DSA Python
graph = {
    'A': ['B', 'C'],
    'B': ['D', 'E'],
    'C': ['F'],
    'D': [],
    'E': [],
    'F': []
}

visited = set()
result = []

def dfs(node):
    if node not in visited:
        visited.add(node)
        result.append(node)
        for neighbor in graph[node]:
            dfs(neighbor)

dfs('A')
print(result)
A['A', 'B', 'D', 'E', 'C', 'F']
B['A', 'C', 'F', 'B', 'D', 'E']
C['A', 'B', 'E', 'D', 'C', 'F']
D['A', 'C', 'B', 'D', 'E', 'F']
Attempts:
2 left
💡 Hint
Remember DFS explores as far as possible along each branch before backtracking.
🧠 Conceptual
intermediate
1:30remaining
Number of nodes visited in DFS
Given the graph below and starting DFS from node '1', how many nodes will be visited?
DSA Python
graph = {
    1: [2, 3],
    2: [4],
    3: [],
    4: [5],
    5: []
}

visited = set()

def dfs(node):
    if node not in visited:
        visited.add(node)
        for neighbor in graph[node]:
            dfs(neighbor)

dfs(1)
print(len(visited))
A2
B3
C5
D4
Attempts:
2 left
💡 Hint
Count all nodes reachable from node 1.
🔧 Debug
advanced
1:30remaining
Identify the error in DFS implementation
What error will the following DFS code produce when run?
DSA Python
graph = {'X': ['Y'], 'Y': ['Z'], 'Z': []}
visited = set()
result = []

def dfs(node):
    if node not in visited:
        visited.add(node)
        result.append(node)
        for neighbor in graph[node]:
            dfs(neighbor)

dfs('A')
print(result)
AKeyError
BTypeError
CIndexError
DNo error, prints ['A']
Attempts:
2 left
💡 Hint
Check if the starting node exists in the graph keys.
❓ Predict Output
advanced
2:00remaining
DFS traversal order with cycle in graph
What is the output of the DFS traversal starting from node 1 on the graph with a cycle?
DSA Python
graph = {
    1: [2],
    2: [3],
    3: [1, 4],
    4: []
}
visited = set()
result = []

def dfs(node):
    if node not in visited:
        visited.add(node)
        result.append(node)
        for neighbor in graph[node]:
            dfs(neighbor)

dfs(1)
print(result)
A[1, 2, 4, 3]
B[1, 2, 3, 4]
C[1, 2, 3]
D[1, 3, 2, 4]
Attempts:
2 left
💡 Hint
DFS should not revisit nodes already visited, even with cycles.
🚀 Application
expert
2:30remaining
DFS to find if path exists between two nodes
Which option correctly returns True if there is a path from start to end in the graph using DFS, otherwise False?
DSA Python
graph = {
    'start': ['a', 'b'],
    'a': ['c'],
    'b': ['d'],
    'c': ['end'],
    'd': [],
    'end': []
}

def has_path(graph, start, end, visited=None):
    if visited is None:
        visited = set()
    if start == end:
        return True
    if start in visited:
        return False
    visited.add(start)
    for neighbor in graph.get(start, []):
        if has_path(graph, neighbor, end, visited):
            return True
    return False

print(has_path(graph, 'start', 'end'))
ATypeError
BFalse
CKeyError
DTrue
Attempts:
2 left
💡 Hint
DFS explores neighbors recursively and returns True if end is found.

Practice

(1/5)
1. What does DFS (Depth First Search) do when exploring a graph?
easy
A. It explores as far as possible along each branch before backtracking.
B. It explores all neighbors at the current depth before going deeper.
C. It visits nodes randomly without any order.
D. It only visits nodes with the highest value first.

Solution

  1. Step 1: Understand DFS traversal

    DFS explores a graph by going deep into one branch before backtracking to explore others.
  2. Step 2: Compare with other traversal methods

    BFS explores neighbors level by level, but DFS goes deep first.
  3. Final Answer:

    It explores as far as possible along each branch before backtracking. -> Option A
  4. Quick Check:

    DFS = deep exploration first [OK]
Hint: DFS means go deep first, then backtrack [OK]
Common Mistakes:
  • Confusing DFS with BFS
  • Thinking DFS visits nodes randomly
  • Assuming DFS visits nodes by value
2. Which of the following is the correct Python syntax to start a DFS function on a graph represented as adjacency list graph from node start?
easy
A. def dfs(start, graph):
B. def dfs(graph, start):
C. def dfs(graph):
D. def dfs(start):

Solution

  1. Step 1: Identify required parameters for DFS

    DFS needs the graph and the starting node to begin traversal.
  2. Step 2: Check function signature correctness

    def dfs(graph, start): correctly defines a function with parameters (graph, start).
  3. Final Answer:

    def dfs(graph, start): -> Option B
  4. Quick Check:

    DFS needs graph and start node [OK]
Hint: DFS function needs graph and start node parameters [OK]
Common Mistakes:
  • Swapping parameter order incorrectly
  • Missing one of the parameters
  • Using only one parameter when two are needed
3. What is the output of the following DFS traversal starting from node 0?
graph = {0: [1, 2], 1: [2], 2: [0, 3], 3: [3]}
visited = set()
def dfs(node):
    if node not in visited:
        print(node, end=' ')
        visited.add(node)
        for neighbor in graph[node]:
            dfs(neighbor)
dfs(0)
medium
A. 0 3 2 1
B. 0 2 3 1
C. 0 1 3 2
D. 0 1 2 3

Solution

  1. Step 1: Start DFS from node 0

    Visit 0, mark visited. Neighbors: 1, 2.
  2. Step 2: Visit neighbor 1

    Visit 1, mark visited. Neighbor: 2.
  3. Step 3: Visit neighbor 2

    Visit 2, mark visited. Neighbors: 0 (visited), 3.
  4. Step 4: Visit neighbor 3

    Visit 3, mark visited. Neighbor: 3 (already visited).
  5. Final Answer:

    0 1 2 3 -> Option D
  6. Quick Check:

    DFS order = 0 1 2 3 [OK]
Hint: Follow neighbors depth-first, avoid revisiting nodes [OK]
Common Mistakes:
  • Visiting neighbors in wrong order
  • Revisiting already visited nodes
  • Confusing BFS order with DFS
4. Find the error in this DFS code snippet and select the fix:
graph = {0: [1], 1: [2], 2: []}
visited = set()
def dfs(node):
    if node in visited:
        return
    print(node)
    for neighbor in graph[node]:
        dfs(neighbor)
dfs(0)
medium
A. Add 'visited.add(node)' after printing node to mark it visited.
B. Change 'if node in visited' to 'if node not in visited'.
C. Remove the 'return' statement inside the if condition.
D. Add 'visited.remove(node)' after recursive calls.

Solution

  1. Step 1: Identify missing visited marking

    The code never adds nodes to visited, so it revisits nodes infinitely.
  2. Step 2: Fix by adding visited marking

    Adding 'visited.add(node)' after printing marks node as visited to avoid revisits.
  3. Final Answer:

    Add 'visited.add(node)' after printing node to mark it visited. -> Option A
  4. Quick Check:

    Mark visited after visiting node [OK]
Hint: Always add node to visited set after visiting [OK]
Common Mistakes:
  • Forgetting to mark nodes visited
  • Incorrect if condition logic
  • Removing nodes from visited incorrectly
5. Given a directed graph represented as adjacency list:
graph = {0: [1, 2], 1: [2], 2: [3], 3: [1]}
Write the DFS traversal order starting from node 0 that detects cycles by tracking recursion stack. What is the order of nodes visited before detecting a cycle?
hard
A. 0 1 2
B. 0 2 3 1
C. 0 1 2 3
D. 0 2 1 3

Solution

  1. Step 1: Start DFS from node 0 and track recursion stack

    Visit 0, then 1, then 2, then 3. At 3, neighbor 1 is in recursion stack, cycle detected.
  2. Step 2: List nodes visited before cycle detection

    Nodes visited in order: 0, 1, 2, 3 before cycle found.
  3. Final Answer:

    0 1 2 3 -> Option C
  4. Quick Check:

    DFS with cycle detection visits 0 1 2 3 [OK]
Hint: Track recursion stack to detect cycles during DFS [OK]
Common Mistakes:
  • Ignoring recursion stack for cycle detection
  • Stopping traversal too early
  • Visiting nodes in wrong order
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard