Solution: Find if Path Exists in Graph
Let’s solve the Find if Path Exists in Graph problem using the Union Find pattern.
We'll cover the following
Statement
Given a 2D list, edges
, which represents a bidirectional graph. Each vertex is labeled from
Determine whether a valid path exists from the source
vertex to the destination
vertex. If it exists, return TRUE; otherwise, return FALSE.
Constraints:
n
edges.length
edges[i].length
source
,destination
There are no duplicate edges.
There are no self-edges.
Solution
This solution uses the union-find algorithm to find if there exists any path between two nodes in a graph.
The Union
function merges two nodes by connecting their roots for each edge in the graph. A rank system is used, where each node initially is its parent and is given a rank of Union
operation compares the ranks of the roots of the two nodes. The rank is updated by attaching the tree with the smaller rank under the tree with the larger rank. If both trees have the same rank, one tree becomes a subtree of the other, and the rank of the new root is increased by
After going through all the edges, the Find
function checks if the source and destination nodes belong to the same group by looking for their roots. If a node isn’t its root, the find operation follows the chain of parent nodes until it finds the root.
After finding the roots, if both nodes share the same root, there will be a path between them.
Here’s the step-by-step implementation of the solution:
Initialize a union-find object for
n
nodes. This creates two lists:root
: Each element initially is the root of itself.rank
: This is used to merge the smaller tree under the larger tree.
For each edge between nodes
x
andy
:Call the
Union
function and find the roots of bothx
andy
.If their roots are different:
Compare the ranks of both roots and attach the tree with the smaller rank under the tree with the larger one.
Increase the rank by
of the new root.
Do nothing if they have the same roots because no merging is required.
After processing all the edges:
Check if the
source
anddestination
nodes have the same root. If they do:Return TRUE because a path exists between them.
Otherwise, return FALSE if both belong to different roots.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.