Skip to content

Commit

Permalink
Create solution.java
Browse files Browse the repository at this point in the history
  • Loading branch information
vikasahlawat228 authored Dec 16, 2020
1 parent 2b60f7e commit 0c97e03
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions Disjoint Sets/Components in a graph/solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;

public class Solution {

public static void main(String args[]){
int[] parents = new int[30001];

Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a, b;

while(n-->0){

a = sc.nextInt();
b = sc.nextInt();

if(parents[a] == 0) parents[a] = a;
if(parents[b] == 0) parents[b] = a;

//Disjoin set idea, keep updating the representative element of each set.
if(parents[a] != 0 || parents[b] != 0){
int low = Math.min(parents[a], parents[b]);
int high = Math.max(parents[a], parents[b]);
for(int i=0; i<parents.length; i++){
if(parents[i] == high)
//let representative always be the smallest in the set
parents[i] = low;
}
}
}

//convert int[] to Integer[] in order to use Collections.frequency(Integer[], int)
Integer[] newArray = new Integer[parents.length];
int i = 0;
for (int value : parents) {
newArray[i++] = value;
}

List<Integer> ints = Arrays.asList(newArray);
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;

for(int item : newArray) {
if(item != 0) {
int frequency = Collections.frequency(ints, item);
min = Math.min(min, frequency);
max = Math.max(max, frequency);
}
}
System.out.println(min + " " + max);
}

}

0 comments on commit 0c97e03

Please sign in to comment.