Will it also work for directed graph!

will it also work for directed graph!

@Shivani999,
Nope. Imagine a graph like this,

1 -> 2 -> 3
\ -> 4 -/^

Here DSU will detect a cycle, even though it actually isn’t(there’s no node, you can return to after traversing any path).