You are given a directed graph with n nodes labeled from 0 to n - 1, described by a list of directed edges. You are also given two nodes, source and destination.
Starting at source, consider every path that follows the edges of the graph. Determine whether all of these paths are finite and every one of them terminates exactly at destination.
Return true only when the following hold: at least one path leaves source, no reachable path can continue forever (there are no reachable cycles), and every path that can no longer be extended ends at destination. The graph may contain self-loops and parallel edges.
Example 1
Input: n = 3, edges = [[0,1],[0,2]], source = 0, destination = 2
Output: false
The path 0 -> 1 ends at node 1, which has no outgoing edges and is not the destination, so not every path leads to destination.
Example 2
Input: n = 4, edges = [[0,1],[0,2],[1,3],[2,3]], source = 0, destination = 3
Output: true
Both branches 0 -> 1 -> 3 and 0 -> 2 -> 3 terminate at node 3, and there are no cycles, so every path reaches destination.
Constraints
1 <= n <= 10^40 <= edges.length <= 10^4edges[i].length == 20 <= from_i, to_i, source, destination <= n - 1The given graph may have self-loops and parallel edges.See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI