VOOZH about

URL: https://www.geeksforgeeks.org/dsa/difference-between-smallest-and-largest-component-of-the-graph-after-each-query/

⇱ Difference between Smallest and Largest Component of the graph after each Query. - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Difference between Smallest and Largest Component of the graph after each Query.

Last Updated : 23 Jul, 2025

Given an integer N, denoting the total number of nodes in a graph without any edges, you have to process Q queries of the form u, v denoting that you have to add an edge between node u and v, after each query you have to print the size difference between largest component and the smallest component of the graph.

Examples:

Input: N = 2, Q = 1, queries = [[1, 2]]
Output: 0
Explanation:

  • Initial components = {{1}{2}}
  • After query[0]:
    • we have components = {{1, 2}}, Since we have only one component of size 2, the difference is 2-2 = 0.

Input: N = 4, Q = 2, queries = [[1, 2],[2, 4]]
Output: [1, 2]
Explanation:

  • Initial components = {{1},{2},{3},{4}},
  • After query[0]:
    • we have components = {{1, 2},{3},{4}} , So difference is, 2-1 = 1.
  • After query[1]:
    • we have components = {{1, 2, 4},{3}} , So difference is, 3-1 = 2.

Approach: We can use Disjoint-Set-Union(DSU) and Priority Queue(using multiset) to solve this question as discussed below:

For each query of adding an edge between 'u' and 'v' we can use DSU to put both the nodes in the same set and update the size of the set they are in. Now we can put this new size in our multiset and remove the older sizes from it.

Simply print the difference between the maximum and minimum element of the multiset to get the answer for each query.

Firstly we have to construct our DSU functions as per the below steps:

  • Create a parent array of the size N i.e. the total number of nodes. This array will denote the parent of each node(component).
  • make(int i): Initialize parent[i]=i, sizez[i]=1, and for each i insert 1 inside a multiset 'st'. This indicates that each node currently has size 1 and forms a component of its own.
  • find(int v): finds the parent of the component the node 'v' belongs to.
  • Union(int a, int b): Merge the nodes 'a' and 'b' together. Delete the old sizes of 'a' and 'b' from the 'st' and insert the new size formed by the combination of 'a' and 'b'

Now use the below algorithm to solve the problem:

  • Initialize the DSU data structure for each node from 1 to N, using the make function.
  • For each query, Union the nodes u and v.
  • Print the difference between the back and front element of the 'st'.

below is the implementation of the above algorithm:


Output
1
2

Time Complexity: O(Q(logN) + N), where Q is the number of queries and N is the number of nodes.
Auxiliary Space: O(N), where N is the number of nodes.

Comment
Article Tags: