diff --git a/0323_number-of-connected-components-in-an-undirected-graph/README.md b/0323_number-of-connected-components-in-an-undirected-graph/README.md new file mode 100644 index 0000000..5e24caa --- /dev/null +++ b/0323_number-of-connected-components-in-an-undirected-graph/README.md @@ -0,0 +1,22 @@ +You have a graph of `n` nodes. You are given an integer `n` and an array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between `ai` and `bi` in the graph. + +Return _the number of connected components in the graph_. + +Example 1:![](https://assets.leetcode.com/uploads/2021/03/14/conn1-graph.jpg) + + Input: n = 5, edges = [[0,1],[1,2],[3,4]] Output: 2 + +Example 2:![](https://assets.leetcode.com/uploads/2021/03/14/conn2-graph.jpg) + + Input: n = 5, edges = [[0,1],[1,2],[2,3],[3,4]] Output: 1 + +Constraints: + +* `1 <= n <= 2000` +* `1 <= edges.length <= 5000` +* `edges[i].length == 2` +* `0 <= ai <= bi < n` +* `ai != bi` +* There are no repeated edges. + +https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/ diff --git a/0323_number-of-connected-components-in-an-undirected-graph/python3/solution.py b/0323_number-of-connected-components-in-an-undirected-graph/python3/solution.py new file mode 100644 index 0000000..f11e755 --- /dev/null +++ b/0323_number-of-connected-components-in-an-undirected-graph/python3/solution.py @@ -0,0 +1,45 @@ +# Time: O(E · 𝛼(n)) ; 𝛼(n) is inverse Ackermann function +# Space: O(V) + + +class Solution: + def countComponents(self, n: int, edges: List[List[int]]) -> int: + parent = [i for i in range(n)] + + # Or like sizes of the components + rank = [1] * n + + def find(node): + # Parent of node could be itself (i.e, no parent) + current_node = node + + while current_node != parent[current_node]: + # Path compression to speed up union-find + parent[current_node] = parent[parent[current_node]] + current_node = parent[current_node] + + return current_node + + + def union(a, b): + parent_a, parent_b = find(a), find(b) + + if parent_a == parent_b: + return 0 + + if rank[parent_a] > rank[parent_b]: + parent[parent_a] = parent_b + rank[parent_b] += rank[parent_a] + else: + parent[parent_b] = parent_a + rank[parent_a] += rank[parent_b] + + return 1 + + + result = n + for a, b in edges: + result -= union(a, b) + + return result + \ No newline at end of file