Pilot Training - codepath/compsci_guides GitHub Wiki

Unit 10 Session 2 Advanced (Click for link to problem statements)

Problem Highlights

  • 💡 Difficulty: Medium
  • Time to complete: 30-40 mins
  • 🛠️ Topics: Graph Traversal, DFS, Cycle Detection

1: U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Established a set (2-3) of test cases to verify their own solution later.
  • Established a set (1-2) of edge cases to verify their solution handles complexities.
  • Have fully understood the problem and have no clarifying questions.
  • Have you verified any Time/Space Constraints for this problem?
  • Q: What does the flight_prerequisites array represent?
    • A: Each pair [a, b] means that course b must be completed before course a.
  • Q: What is the goal of the problem?
    • A: The goal is to determine whether it is possible to complete all courses given the prerequisites. If there are cycles (e.g., course a requires b, but b also requires a), it would be impossible to complete all courses.
  • Q: How should the function handle cycles in the course graph?
    • A: The function should return False if there is a cycle, meaning it is impossible to complete all courses.
HAPPY CASE
Input: 
```python
flight_prerequisites_1 = ['Advanced Maneuvers', 'Basic Navigation'](/codepath/compsci_guides/wiki/'Advanced-Maneuvers',-'Basic-Navigation')
num_courses = 2
```
Output:
```markdown
True
Explanation: It is possible to take *Advanced Maneuvers* after completing *Basic Navigation*. There is no cycle, so all courses can be completed.
```

EDGE CASE
Input: 
```python
flight_prerequisites_2 = ['Advanced Maneuvers', 'Basic Navigation'], ['Basic Navigation', 'Advanced Maneuvers'](/codepath/compsci_guides/wiki/'Advanced-Maneuvers',-'Basic-Navigation'],-['Basic-Navigation',-'Advanced-Maneuvers')
num_courses = 2
```
Output:
```markdown
False
Explanation: There is a cycle between *Advanced Maneuvers* and *Basic Navigation*. This makes it impossible to complete all courses.

2: M-atch

Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.

For Cycle Detection in a Directed Graph, we want to consider the following approaches:

  • Graph Representation: Build an adjacency list from the prerequisites to represent the course dependencies.
  • Depth First Search (DFS): Use DFS to detect cycles in the graph. If a cycle is detected, it means that it is impossible to complete all courses.

3: P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Represent the course prerequisites as a directed graph. Perform DFS to detect if there are any cycles in the graph. If a cycle exists, return False, as it would be impossible to complete all courses.

1) Build an adjacency list to represent the graph from `flight_prerequisites`.
2) Initialize two arrays:
   - `visited`: To track whether a course has been visited.
   - `recursion_stack`: To track the current recursion stack during DFS, helping detect cycles.
3) Define a recursive DFS function:
   a) If the course is already in the recursion stack, return `False` (cycle detected).
   b) If the course has been visited and is not part of the current recursion stack, return `True`.
   c) Mark the course as visited and add it to the recursion stack.
   d) Recursively perform DFS on all its prerequisite courses.
   e) Remove the course from the recursion stack once all its neighbors are processed.
4) For each course, run DFS to check if a cycle exists.
5) If no cycle is detected, return `True`.

⚠️ Common Mistakes

  • Forgetting to remove the course from the recursion stack after processing, leading to false cycle detection.
  • Not handling the case where the course has no prerequisites (empty neighbors).

4: I-mplement

Implement the code to solve the algorithm.

def can_complete_flight_training(num_courses, flight_prerequisites):
    # Build adjacency list
    graph = {i: [] for i in range(num_courses)}
    for course, prerequisite in flight_prerequisites:
        graph[prerequisite].append(course)
    
    # Track visited courses and current DFS stack
    visited = [False] * num_courses
    recursion_stack = [False] * num_courses
    
    # DFS helper function
    def dfs(course):
        if recursion_stack[course]:  # Cycle detected
            return False
        if visited[course]:  # Already visited this node in a previous DFS
            return True
        
        # Mark the node as visited and part of the current recursion stack
        visited[course] = True
        recursion_stack[course] = True
        
        # Perform DFS on all neighbors (prerequisite courses)
        for neighbor in graph[course]:
            if not dfs(neighbor):
                return False
        
        # Remove the course from the recursion stack after processing
        recursion_stack[course] = False
        return True
    
    # Run DFS for each course
    for course in range(num_courses):
        if not visited[course]:
            if not dfs(course):
                return False
    
    return True

5: R-eview

Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.

  • Input:
flight_prerequisites_1 = ['Advanced Maneuvers', 'Basic Navigation'](/codepath/compsci_guides/wiki/'Advanced-Maneuvers',-'Basic-Navigation')
flight_prerequisites_2 = ['Advanced Maneuvers', 'Basic Navigation'], ['Basic Navigation', 'Advanced Maneuvers'](/codepath/compsci_guides/wiki/'Advanced-Maneuvers',-'Basic-Navigation'],-['Basic-Navigation',-'Advanced-Maneuvers')

print(can_complete_flight_training(2, flight_prerequisites_1))  # Expected output: True
print(can_complete_flight_training(2, flight_prerequisites_2))  # Expected output: False
  • Output:
True
False

6: E-valuate

Evaluate the performance of your algorithm and state any strong/weak or future potential work.

  • Time Complexity: O(V + E), where V is the number of courses (vertices) and E is the number of prerequisite pairs (edges). Each course and prerequisite is visited once in the DFS traversal.
  • Space Complexity: O(V + E) for storing the graph, visited array, and recursion stack.