# Leetcode 1584. How to make my Kruskal&Union Find algorithm faster?

The question was on Leetcode 1584. Min Cost to Connect All Points. My answer to this question is:

class Solution {
public int minCostConnectPoints(int[][] points) {
List<int[]> list = new ArrayList<>();
for(int i = 0; i < points.length; i++){
for(int j = 0; j < points.length; j++){
int dist = Math.abs(points[i] - points[j]) + Math.abs(points[i] - points[j]);
}
}
list.sort((int a[], int b[]) -> a - b);
UnionFindSet uf = new UnionFindSet(points.length);
int totalCost = 0;
for(int edges[] : list){
if(uf.Find(edges) != uf.Find(edges)){
uf.Union(edges,edges);
totalCost += edges;
}
}
}
}

class UnionFindSet {
public final int[] parents;

UnionFindSet(int size) {
this.parents = new int[size];
for (int i = 0; i < size; i++) {
this.parents[i] = i;
}
}

public int Find(int x) {
if (this.parents[x] != x) {
this.parents[x] = Find(this.parents[x]);
}
return this.parents[x];
}

public void Union(int x, int y) {
this.parents[Find(y)] = Find(x);
}
}


My answer can pass all the test cases but the speed is extremely slow. Any idea how could I improve my code to make it faster? One of my guesses is maybe the nested for loop to calculate the Manhattan Distance is expensive, but I don't know how to omit or replace it. Any idea would be appreciated!

Your solution already seems to be implemented (rather) efficiently. My only advice is to rename Find and Union to find and union, respectively (Java style prefers lowercase chars at the first verb of a method name).
In UnionFindSet, you have
public final int[] parents;

I suggest you hide it by the private keyword instead of public.