KatInterview

813. All Paths From Source to Target

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for all paths from a fixed source (node 0) to a fixed target (node n-1) in a Directed Acyclic Graph (DAG). This is a classic graph traversal problem where we need to explore all possibilities, not just find a single path or the shortest one. Depth First Search (DFS) is a natural fit for this kind of exhaustive path-finding problem because it explores one path to its conclusion before backtracking to try other options.

Solution

All Paths From Source to Target in Python

class Solution:
    def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
        target = len(graph) - 1
        result = []
        path = [0]

        def dfs(current_node):
            # If the current node is the target, we've found a valid path.
            if current_node == target:
                # Add a copy of the current path to the result list.
                # In Python, path[:] or list(path) creates a shallow copy.
                result.append(list(path))
                return

            # Explore all neighbors of the current node.
            for next_node in graph[current_node]:
                # Add the neighbor to the current path.
                path.append(next_node)
                
                # Recursively call dfs for the neighbor.
                dfs(next_node)
                
                # Backtrack: remove the neighbor from the path to explore other branches.
                path.pop()
        
        # Start the DFS from the source node 0.
        dfs(0)
        return result

All Paths From Source to Target in Java

class Solution {
    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        int target = graph.length - 1;

        // The path always starts with node 0.
        path.add(0);

        dfs(graph, 0, target, path, result);

        return result;
    }

    private void dfs(int[][] graph, int currentNode, int target, List<Integer> path, List<List<Integer>> result) {
        // If the current node is the target, we've found a valid path.
        if (currentNode == target) {
            // Add a copy of the current path to the result list. A new ArrayList is created for the copy.
            result.add(new ArrayList<>(path));
            return;
        }

        // Explore all neighbors of the current node.
        for (int nextNode : graph[currentNode]) {
            // Add the neighbor to the current path.
            path.add(nextNode);

            // Recursively call dfs for the neighbor.
            dfs(graph, nextNode, target, path, result);

            // Backtrack: remove the neighbor from the path to explore other branches.
            path.remove(path.size() - 1);
        }
    }
}

All Paths From Source to Target in C++

class Solution {
public:
    vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
        vector<vector<int>> result;
        vector<int> path;
        int target = graph.size() - 1;
        
        // The path always starts with node 0.
        path.push_back(0);
        
        dfs(graph, 0, target, path, result);
        
        return result;
    }

private:
    void dfs(vector<vector<int>>& graph, int currentNode, int target, vector<int>& path, vector<vector<int>>& result) {
        // If the current node is the target, we've found a valid path.
        if (currentNode == target) {
            // Add a copy of the current path to the result list.
            result.push_back(path);
            return;
        }

        // Explore all neighbors of the current node.
        for (int nextNode : graph[currentNode]) {
            // Add the neighbor to the current path.
            path.push_back(nextNode);
            
            // Recursively call dfs for the neighbor.
            dfs(graph, nextNode, target, path, result);
            
            // Backtrack: remove the neighbor from the path to explore other branches.
            path.pop_back();
        }
    }
};

All Paths From Source to Target in TypeScript

function allPathsSourceTarget(graph: number[][]): number[][] {
    const target = graph.length - 1;
    const result: number[][] = [];
    const path: number[] = [0]; // The path always starts with node 0.

    function dfs(currentNode: number) {
        // If the current node is the target, we've found a valid path.
        if (currentNode === target) {
            // Add a copy of the current path to the result list.
            // The spread syntax `[...path]` creates a shallow copy of the array.
            result.push([...path]);
            return;
        }

        // Explore all neighbors of the current node.
        for (const nextNode of graph[currentNode]) {
            // Add the neighbor to the current path.
            path.push(nextNode);
            
            // Recursively call dfs for the neighbor.
            dfs(nextNode);
            
            // Backtrack: remove the neighbor from the path to explore other branches.
            path.pop();
        }
    }

    // Start the DFS from the source node 0.
    dfs(0);
    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.