KatInterview

511. All Paths from Source Lead to Destination

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 whether all paths starting from a source node in a directed graph eventually lead to and terminate at a destination node. This requirement can be broken down into three specific conditions for every path originating from the source:

Solution

All Paths from Source Lead to Destination in Python

class Solution:
    def leadsToDestination(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:
        adj = [[] for _ in range(n)]
        for u, v in edges:
            adj[u].append(v)
        
        # states: 0: UNKNOWN, 1: VISITING, 2: SAFE, 3: UNSAFE
        states = [0] * n
        
        return self.dfs(source, destination, adj, states)

    def dfs(self, u: int, destination: int, adj: List[List[int]], states: List[int]) -> bool:
        # If the state is already computed, return the cached result.
        # VISITING (1) implies a cycle, which is unsafe. SAFE (2) is safe.
        # UNSAFE (3) is unsafe. So, we return true only if state is SAFE (2).
        if states[u] != 0:
            return states[u] == 2

        # Mark the current node as VISITING
        states[u] = 1
        
        # If it's a terminal node (no outgoing edges)
        if not adj[u]:
            is_dest = (u == destination)
            states[u] = 2 if is_dest else 3  # Cache result: SAFE or UNSAFE
            return is_dest
        
        # Recursively call DFS for all neighbors
        for v in adj[u]:
            if not self.dfs(v, destination, adj, states):
                # If any path from a neighbor is unsafe, this path is also unsafe.
                states[u] = 3  # Mark as UNSAFE
                return False
        
        # If all paths from all neighbors are safe, this node is also safe.
        states[u] = 2  # Mark as SAFE
        return True

All Paths from Source Lead to Destination in Java

class Solution {
    // states: 0: UNKNOWN, 1: VISITING, 2: SAFE, 3: UNSAFE
    private int[] states;
    private List<List<Integer>> adj;
    private int destination;

    public boolean leadsToDestination(int n, int[][] edges, int source, int destination) {
        // Build adjacency list
        adj = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            adj.add(new ArrayList<>());
        }
        for (int[] edge : edges) {
            adj.get(edge[0]).add(edge[1]);
        }
        
        this.states = new int[n];
        this.destination = destination;
        
        return dfs(source);
    }

    private boolean dfs(int u) {
        // If the state is already computed, return the cached result.
        // VISITING (1) implies a cycle, which is unsafe. SAFE (2) is safe.
        // UNSAFE (3) is unsafe. So, we return true only if state is SAFE (2).
        if (states[u] != 0) {
            return states[u] == 2;
        }
        
        // Mark the current node as VISITING
        states[u] = 1;
        
        // If it's a terminal node (no outgoing edges)
        if (adj.get(u).isEmpty()) {
            boolean isDest = (u == destination);
            states[u] = isDest ? 2 : 3; // Cache result: SAFE or UNSAFE
            return isDest;
        }
        
        // Recursively call DFS for all neighbors
        for (int v : adj.get(u)) {
            if (!dfs(v)) {
                // If any path from a neighbor is unsafe, this path is also unsafe.
                states[u] = 3; // Mark as UNSAFE
                return false;
            }
        }
        
        // If all paths from all neighbors are safe, this node is also safe.
        states[u] = 2; // Mark as SAFE
        return true;
    }
}

All Paths from Source Lead to Destination in C++

class Solution {
public:
    bool leadsToDestination(int n, vector<vector<int>>& edges, int source, int destination) {
        // Build adjacency list
        vector<vector<int>> adj(n);
        for (const auto& edge : edges) {
            adj[edge[0]].push_back(edge[1]);
        }
        
        // states: 0: UNKNOWN, 1: VISITING, 2: SAFE, 3: UNSAFE
        vector<int> states(n, 0);
        
        return dfs(source, destination, adj, states);
    }

private:
    bool dfs(int u, int destination, vector<vector<int>>& adj, vector<int>& states) {
        // If the state is already computed, return the cached result.
        // VISITING (1) implies a cycle, which is unsafe. SAFE (2) is safe.
        // UNSAFE (3) is unsafe. So, we return true only if state is SAFE (2).
        if (states[u] != 0) {
            return states[u] == 2;
        }
        
        // Mark the current node as VISITING
        states[u] = 1;
        
        // If it's a terminal node (no outgoing edges)
        if (adj[u].empty()) {
            bool is_dest = (u == destination);
            states[u] = is_dest ? 2 : 3; // Cache result: SAFE or UNSAFE
            return is_dest;
        }
        
        // Recursively call DFS for all neighbors
        for (int v : adj[u]) {
            if (!dfs(v, destination, adj, states)) {
                // If any path from a neighbor is unsafe, this path is also unsafe.
                states[u] = 3; // Mark as UNSAFE
                return false;
            }
        }
        
        // If all paths from all neighbors are safe, this node is also safe.
        states[u] = 2; // Mark as SAFE
        return true;
    }
};

All Paths from Source Lead to Destination in TypeScript

function leadsToDestination(n: number, edges: number[][], source: number, destination: number): boolean {
    // Build adjacency list
    const adj: number[][] = Array.from({ length: n }, () => []);
    for (const [u, v] of edges) {
        adj[u].push(v);
    }
    
    // states: 0: UNKNOWN, 1: VISITING, 2: SAFE, 3: UNSAFE
    const states: number[] = new Array(n).fill(0);
    
    const dfs = (u: number): boolean => {
        // If the state is already computed, return the cached result.
        // VISITING (1) implies a cycle, which is unsafe. SAFE (2) is safe.
        // UNSAFE (3) is unsafe. So, we return true only if state is SAFE (2).
        if (states[u] !== 0) {
            return states[u] === 2;
        }

        // Mark the current node as VISITING
        states[u] = 1;

        // If it's a terminal node (no outgoing edges)
        if (adj[u].length === 0) {
            const isDest = u === destination;
            states[u] = isDest ? 2 : 3; // Cache result: SAFE or UNSAFE
            return isDest;
        }

        // Recursively call DFS for all neighbors
        for (const v of adj[u]) {
            if (!dfs(v)) {
                // If any path from a neighbor is unsafe, this path is also unsafe.
                states[u] = 3; // Mark as UNSAFE
                return false;
            }
        }

        // If all paths from all neighbors are safe, this node is also safe.
        states[u] = 2; // Mark as SAFE
        return true;
    };
    
    return dfs(source);
}

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.