Problem solution · Java

GCD Sort of an Array

GCD Sort of an Array: a Java solution using disjoint set union. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Disjoint set union
Source
walkccc LeetCode Solutions
Length
76 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Disjoint set union

For GCD Sort of an Array, the implementation maintains connected components and merges them as relationships are processed.

  1. Give each element a component representative.
  2. Merge representatives when a connection is accepted.
  3. Answer connectivity or component queries from the compressed representatives.

Code notes

  • 76 lines of Java from the credited upstream file 1998.java.
  • The implementation visibly relies on sequence storage.
  • 9 loop blocks detected.

Complexity

Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeGCD Sort of an Array · JavaJava
Use this to learn the idea, then write your own version.
class UnionFind {  public UnionFind(int n) {    id = new int[n];    rank = new int[n];    for (int i = 0; i < n; ++i)      id[i] = i;  }   public void unionByRank(int u, int v) {    final int i = find(u);    final int j = find(v);    if (i == j)      return;    if (rank[i] < rank[j]) {      id[i] = j;    } else if (rank[i] > rank[j]) {      id[j] = i;    } else {      id[i] = j;      ++rank[j];    }  }   public int find(int u) {    return id[u] == u ? u : (id[u] = find(id[u]));  }   private int[] id;  private int[] rank;} class Solution {  public boolean gcdSort(int[] nums) {    final int mx = Arrays.stream(nums).max().getAsInt();    final int[] minPrimeFactors = sieveEratosthenes(mx + 1);    UnionFind uf = new UnionFind(mx + 1);     for (final int num : nums)      for (final int primeFactor : getPrimeFactors(num, minPrimeFactors))        uf.unionByRank(num, primeFactor);     int[] sortedNums = nums.clone();    Arrays.sort(sortedNums);     for (int i = 0; i < nums.length; ++i)      // Can't swap nums[i] with sortedNums[i].      if (uf.find(nums[i]) != uf.find(sortedNums[i]))        return false;     return true;  }   // Gets the minimum prime factor of i, where 1 < i <= n.  private int[] sieveEratosthenes(int n) {    int[] minPrimeFactors = new int[n + 1];    for (int i = 2; i <= n; ++i)      minPrimeFactors[i] = i;    for (int i = 2; i * i < n; ++i)      if (minPrimeFactors[i] == i) // `i` is prime.        for (int j = i * i; j < n; j += i)          minPrimeFactors[j] = Math.min(minPrimeFactors[j], i);    return minPrimeFactors;  }   private List<Integer> getPrimeFactors(int num, int[] minPrimeFactors) {    List<Integer> primeFactors = new ArrayList<>();    while (num > 1) {      final int divisor = minPrimeFactors[num];      primeFactors.add(divisor);      while (num % divisor == 0)        num /= divisor;    }    return primeFactors;  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗