You have a graph of n nodes labeled from 0 to n - 1. You are given an integer n and an array edges where edges[i] = [a_i, b_i] indicates that there is an edge between a_i and b_i in the graph. Return the number of connected components in the graph.
Example 1
Input: n = 5, edges = [[0,1],[1,2],[3,4]]
Output: 2
Explanation: The edges 0-1 and 1-2 join nodes 0, 1 and 2 into one component, and the edge 3-4 joins nodes 3 and 4 into another. That makes 2 components.
Example 2
Input: n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
Output: 1
Explanation: The edges form a single chain 0-1-2-3-4, so all nodes are in one component.
Example 3
Input: n = 4, edges = []
Output: 4
Explanation: There are no edges, so each of the 4 nodes is its own component.
Start with n separate components. Every edge that unites two different sets merges two components into one, decrementing the count.
Run checks all cases above. Submit evaluates all test cases.