Problem solution · Java

Remove Max Number of Edges to Keep Graph Fully Traversable

Remove Max Number of Edges to Keep Graph Fully Traversable: 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
74 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 Remove Max Number of Edges to Keep Graph Fully Traversable, 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

  • 74 lines of Java from the credited upstream file 1579.java.
  • The implementation visibly relies on sequence storage.
  • 2 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 codeRemove Max Number of Edges to Keep Graph Fully Traversable · JavaJava
Use this to learn the idea, then write your own version.
class UnionFind {  public UnionFind(int n) {    count = n;    id = new int[n];    rank = new int[n];    for (int i = 0; i < n; ++i)      id[i] = i;  }   public boolean unionByRank(int u, int v) {    final int i = find(u);    final int j = find(v);    if (i == j)      return false;    if (rank[i] < rank[j]) {      id[i] = j;    } else if (rank[i] > rank[j]) {      id[j] = i;    } else {      id[i] = j;      ++rank[j];    }    --count;    return true;  }   public int getCount() {    return count;  }   private int count;  private int[] id;  private int[] rank;   private int find(int u) {    return id[u] == u ? u : (id[u] = find(id[u]));  }} class Solution {  public int maxNumEdgesToRemove(int n, int[][] edges) {    UnionFind alice = new UnionFind(n);    UnionFind bob = new UnionFind(n);    int requiredEdges = 0;     // Greedily put type 3 edges in the front.    Arrays.sort(edges, Comparator.comparingInt(edge -> - edge[0]));     for (int[] edge : edges) {      final int type = edge[0];      final int u = edge[1] - 1;      final int v = edge[2] - 1;      switch (type) {        case 3: // Can be traversed by Alice and Bob.          // Note that we should use | instead of || because if the first          // expression is true, short-circuiting will skip the second          // expression.          if (alice.unionByRank(u, v) | bob.unionByRank(u, v))            ++requiredEdges;          break;        case 2: // Can be traversed by Bob.          if (bob.unionByRank(u, v))            ++requiredEdges;          break;        case 1: // Can be traversed by Alice.          if (alice.unionByRank(u, v))            ++requiredEdges;      }    }     return alice.getCount() == 1 && bob.getCount() == 1 ? edges.length - requiredEdges : -1;  }} 

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 ↗