323. Number of Connected Components in an Undirected Graph
Union-Find : union(int p, int q), find(int p)
time complexity: find: O(1), so overall: O(E)
space complexity: O(V)
DFS=> build graph, then check the visited vertex
Complexity Analysis
Here EE = Number of edges, VV = Number of vertices.
Time complexity: {O}(E + V)O(E+V).
Building the adjacency list will take {O}(E)O(E) operations, as we iterate over the list of edges once, and insert each edge into two lists.
During the DFS traversal, each vertex will only be visited once. This is because we mark each vertex as visited as soon as we see it, and then we only visit vertices that are not marked as visited. In addition, when we iterate over the edge list of each vertex, we look at each edge once. This has a total cost of {O}(E + V)O(E+V).
Space complexity: {O}(E + V)O(E+V).
Building the adjacency list will take {O}(E)O(E) space. To keep track of visited vertices, an array of size {O}(V)O(V) is required. Also, the run-time stack for DFS will use {O}(V)O(V) space.
Last updated
Was this helpful?