Problem solution · Java

Rank Transform of a Matrix

Rank Transform of a Matrix: 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
75 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 Rank Transform of a Matrix, 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

  • 75 lines of Java from the credited upstream file 1632.java.
  • The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
  • 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 codeRank Transform of a Matrix · JavaJava
Use this to learn the idea, then write your own version.
class UnionFind {  public void union(int u, int v) {    id.putIfAbsent(u, u);    id.putIfAbsent(v, v);    final int i = find(u);    final int j = find(v);    if (i != j)      id.put(i, j);  }   public Map<Integer, List<Integer>> getGroupIdToValues() {    Map<Integer, List<Integer>> groupIdToValues = new HashMap<>();    for (Map.Entry<Integer, Integer> entry : id.entrySet()) {      final int u = entry.getKey();      final int i = find(u);      groupIdToValues.putIfAbsent(i, new ArrayList<>());      groupIdToValues.get(i).add(u);    }    return groupIdToValues;  }   private Map<Integer, Integer> id = new HashMap<>();   private int find(int u) {    return id.getOrDefault(u, u) == u ? u : find(id.get(u));  }} class Solution {  public int[][] matrixRankTransform(int[][] matrix) {    final int m = matrix.length;    final int n = matrix[0].length;    int[][] ans = new int[m][n];    // {val: [(i, j)]}    TreeMap<Integer, List<Pair<Integer, Integer>>> valToGrids = new TreeMap<>();    // rank[i] := the maximum rank of the row or column so far    int[] maxRankSoFar = new int[m + n];     for (int i = 0; i < m; ++i)      for (int j = 0; j < n; ++j) {        final int val = matrix[i][j];        valToGrids.putIfAbsent(val, new ArrayList<>());        valToGrids.get(val).add(new Pair<>(i, j));      }     for (Map.Entry<Integer, List<Pair<Integer, Integer>>> entry : valToGrids.entrySet()) {      final int val = entry.getKey();      List<Pair<Integer, Integer>> grids = entry.getValue();      UnionFind uf = new UnionFind();      for (Pair<Integer, Integer> grid : grids) {        final int i = grid.getKey();        final int j = grid.getValue();        // Union i-th row with j-th col.        uf.union(i, j + m);      }      for (List<Integer> values : uf.getGroupIdToValues().values()) {        // Get the maximum rank of all the included rows and columns.        int maxRank = 0;        for (final int i : values)          maxRank = Math.max(maxRank, maxRankSoFar[i]);        // Update all the rows and columns to maxRank + 1.        for (final int i : values)          maxRankSoFar[i] = maxRank + 1;      }      for (Pair<Integer, Integer> grid : grids) {        final int i = grid.getKey();        final int j = grid.getValue();        ans[i][j] = maxRankSoFar[i];      }    }     return ans;  }} 

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 ↗