Solving Leetcode Interviews in Seconds with AI: All Paths From Source to Target
Introduction
In this blog post, we will explore how to solve the LeetCode problem "797" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order. The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]). Example 1: Input: graph = [[1,2],[3],[3],[]] Output: [[0,1,3],[0,2,3]] Explanation: There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3. Example 2: Input: graph = [[4,3,1],[3,2,4],[3],[4],[]] Output: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]] Constraints: n == graph.length 2 <= n <= 15 0 <= graph[i][j] < n graph[i][j] != i (i.e., there will be no self-loops). All the elements of graph[i] are unique. The input graph is guaranteed to be a DAG.
Explanation
Here's the solution to find all paths in a DAG from node 0 to node n-1:
Depth-First Search (DFS): Employ DFS to explore all possible paths starting from the source node (0).
Path Tracking: Maintain a list to keep track of the current path being explored.
Destination Check: When the destination node (n-1) is reached, add a copy of the current path to the result list.
Time & Space Complexity: O(2n n), where n is the number of nodes. Space complexity is O(n) due to the recursive call stack and path storage, though in worst-case scenario of full binary tree it can reach up to O(2n n) due to storage of result.
Code
def allPathsSourceTarget(graph):
"""
Finds all possible paths from node 0 to node n-1 in a DAG.
Args:
graph: A list of lists representing the adjacency list of the graph.
Returns:
A list of lists, where each inner list represents a path from 0 to n-1.
"""
n = len(graph)
result = []
def dfs(node, path):
"""
Performs Depth-First Search to find all paths.
Args:
node: The current node being visited.
path: The current path being explored.
"""
path.append(node)
if node == n - 1:
result.append(path.copy()) # Add a copy to avoid modification
else:
for neighbor in graph[node]:
dfs(neighbor, path)
path.pop() # Backtrack: Remove the current node after exploring its neighbors
dfs(0, [])
return result