Bird
Raised Fist0
Data Structures Theoryknowledge~10 mins

Cycle detection in graphs in Data Structures Theory - Interactive Code Practice

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to check if a graph has a cycle using DFS.

Data Structures Theory
def dfs(node, visited, rec_stack):
    visited.add(node)
    rec_stack.add(node)
    for neighbor in graph[node]:
        if neighbor not in visited:
            if dfs(neighbor, visited, rec_stack):
                return True
        elif neighbor in [1]:
            return True
    rec_stack.remove(node)
    return False
Drag options to blanks, or click blank then click option'
Arec_stack
Bvisited
Cgraph
Dstack
Attempts:
3 left
💡 Hint
Common Mistakes
Checking if neighbor is in visited instead of recursion stack.
Not removing node from recursion stack after DFS call.
2fill in blank
medium

Complete the code to initialize the visited set before DFS traversal.

Data Structures Theory
visited = set()
for node in graph:
    if node not in [1]:
        if dfs(node, visited, set()):
            print("Cycle detected")
Drag options to blanks, or click blank then click option'
Avisited
Brec_stack
Cstack
Dgraph
Attempts:
3 left
💡 Hint
Common Mistakes
Checking membership in recursion stack instead of visited.
Starting DFS on all nodes without checking visited.
3fill in blank
hard

Fix the error in the cycle detection condition inside DFS.

Data Structures Theory
if neighbor in visited and neighbor in [1]:
    return True
Drag options to blanks, or click blank then click option'
Avisited
Brec_stack
Cgraph
Dstack
Attempts:
3 left
💡 Hint
Common Mistakes
Checking only visited set for cycle detection.
Confusing recursion stack with visited set.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps each node to its neighbors count and filters nodes with more than 2 neighbors.

Data Structures Theory
neighbor_counts = {node: len(graph[node]) for node in graph if len(graph[node]) [1] [2]
Drag options to blanks, or click blank then click option'
A>
B2
C<
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using less than or equal instead of greater than.
Confusing the order of operator and number.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps uppercase node names to their neighbor count, filtering nodes with at least 1 neighbor.

Data Structures Theory
result = { [1]: len(graph[node]) for node in graph if len(graph[node]) [2] [3]
Drag options to blanks, or click blank then click option'
Anode.upper()
B>=
C1
Dnode.lower()
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase instead of uppercase for node names.
Using less than instead of greater than or equal for filtering.

Practice

(1/5)
1. What is the main purpose of cycle detection in a graph?
easy
A. To count the number of nodes
B. To find if there is a loop in the graph
C. To sort the nodes in ascending order
D. To find the shortest path between nodes

Solution

  1. Step 1: Understand the concept of cycle detection

    Cycle detection checks if a graph contains any loops where you can start at a node and return to it by following edges.
  2. Step 2: Identify the main goal

    The main goal is to find if such loops exist, which can cause problems like infinite loops in algorithms.
  3. Final Answer:

    To find if there is a loop in the graph -> Option B
  4. Quick Check:

    Cycle detection = find loops [OK]
Hint: Cycle detection means finding loops in graphs [OK]
Common Mistakes:
  • Confusing cycle detection with sorting
  • Thinking it counts nodes instead of finding loops
  • Assuming it finds shortest paths
2. Which data structure is commonly used to detect cycles in a directed graph using DFS?
easy
A. Queue
B. Stack
C. Hash Set to track recursion stack
D. Priority Queue

Solution

  1. Step 1: Recall DFS cycle detection method

    DFS explores nodes deeply and uses a recursion stack to track nodes currently in the path.
  2. Step 2: Identify the data structure used

    A hash set or boolean array is used to track nodes in the recursion stack to detect back edges indicating cycles.
  3. Final Answer:

    Hash Set to track recursion stack -> Option C
  4. Quick Check:

    DFS cycle detection uses recursion stack tracking [OK]
Hint: Use a hash set to track nodes in current DFS path [OK]
Common Mistakes:
  • Using queue instead of stack for DFS
  • Not tracking recursion stack nodes
  • Confusing with BFS cycle detection
3. Consider the directed graph edges: [(1, 2), (2, 3), (3, 4), (4, 2)]. Does this graph contain a cycle?
medium
A. Yes, there is a cycle involving nodes 2, 3, and 4
B. Yes, but only between nodes 1 and 2
C. No, it is acyclic
D. No, because node 1 has no incoming edges

Solution

  1. Step 1: Trace the edges to find cycles

    Edges form path 1->2->3->4 and then 4->2, which loops back to node 2.
  2. Step 2: Identify the cycle nodes

    The cycle is formed by nodes 2, 3, and 4 because you can go from 2 to 3 to 4 and back to 2.
  3. Final Answer:

    Yes, there is a cycle involving nodes 2, 3, and 4 -> Option A
  4. Quick Check:

    Edges 4->2 create cycle 2-3-4 [OK]
Hint: Look for edges that point back to earlier nodes [OK]
Common Mistakes:
  • Ignoring the edge 4->2 that closes the cycle
  • Thinking node 1's edges affect cycle
  • Assuming no cycle if start node has no incoming edges
4. Given this DFS-based cycle detection pseudocode, what is the error?
function dfs(node):
  visited[node] = true
  for neighbor in graph[node]:
    if visited[neighbor]:
      return true
    if dfs(neighbor):
      return true
  return false
medium
A. It does not track nodes in the current recursion stack
B. It marks nodes as visited too late
C. It should use a queue instead of recursion
D. It returns false too early

Solution

  1. Step 1: Analyze the visited marking

    The code marks nodes as visited but does not distinguish between nodes visited in current path and fully processed nodes.
  2. Step 2: Identify missing recursion stack tracking

    Without tracking nodes in the current recursion stack, it cannot detect back edges properly, causing false negatives.
  3. Final Answer:

    It does not track nodes in the current recursion stack -> Option A
  4. Quick Check:

    Missing recursion stack tracking causes wrong cycle detection [OK]
Hint: Track recursion stack separately to detect cycles [OK]
Common Mistakes:
  • Using only visited array without recursion stack
  • Confusing visited with recursion stack
  • Thinking recursion depth causes error
5. You have a task scheduling system represented as a directed graph where edges mean "task A must finish before task B starts." How can cycle detection help in this system?
hard
A. It counts the total number of tasks
B. It finds tasks that can run in parallel
C. It sorts tasks by their duration
D. It detects impossible schedules due to circular dependencies

Solution

  1. Step 1: Understand task scheduling graph meaning

    Edges show dependencies; a cycle means tasks depend on each other in a loop.
  2. Step 2: Identify the role of cycle detection

    If a cycle exists, the schedule is impossible because tasks wait on each other endlessly.
  3. Final Answer:

    It detects impossible schedules due to circular dependencies -> Option D
  4. Quick Check:

    Cycle detection finds circular dependencies [OK]
Hint: Cycles mean tasks depend on each other endlessly [OK]
Common Mistakes:
  • Thinking cycle detection sorts tasks
  • Assuming cycles allow parallel tasks
  • Confusing cycle detection with counting tasks