- Give each element a component representative.
- Merge representatives when a connection is accepted.
- 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.
Use this to learn the idea, then write your own version.
1class UnionFind {2 public void union(int u, int v) {3 id.putIfAbsent(u, u);4 id.putIfAbsent(v, v);5 final int i = find(u);6 final int j = find(v);7 if (i != j)8 id.put(i, j);9 }10 11 public Map<Integer, List<Integer>> getGroupIdToValues() {12 Map<Integer, List<Integer>> groupIdToValues = new HashMap<>();13 for (Map.Entry<Integer, Integer> entry : id.entrySet()) {14 final int u = entry.getKey();15 final int i = find(u);16 groupIdToValues.putIfAbsent(i, new ArrayList<>());17 groupIdToValues.get(i).add(u);18 }19 return groupIdToValues;20 }21 22 private Map<Integer, Integer> id = new HashMap<>();23 24 private int find(int u) {25 return id.getOrDefault(u, u) == u ? u : find(id.get(u));26 }27}28 29class Solution {30 public int[][] matrixRankTransform(int[][] matrix) {31 final int m = matrix.length;32 final int n = matrix[0].length;33 int[][] ans = new int[m][n];34 35 TreeMap<Integer, List<Pair<Integer, Integer>>> valToGrids = new TreeMap<>();36 37 int[] maxRankSoFar = new int[m + n];38 39 for (int i = 0; i < m; ++i)40 for (int j = 0; j < n; ++j) {41 final int val = matrix[i][j];42 valToGrids.putIfAbsent(val, new ArrayList<>());43 valToGrids.get(val).add(new Pair<>(i, j));44 }45 46 for (Map.Entry<Integer, List<Pair<Integer, Integer>>> entry : valToGrids.entrySet()) {47 final int val = entry.getKey();48 List<Pair<Integer, Integer>> grids = entry.getValue();49 UnionFind uf = new UnionFind();50 for (Pair<Integer, Integer> grid : grids) {51 final int i = grid.getKey();52 final int j = grid.getValue();53 54 uf.union(i, j + m);55 }56 for (List<Integer> values : uf.getGroupIdToValues().values()) {57 58 int maxRank = 0;59 for (final int i : values)60 maxRank = Math.max(maxRank, maxRankSoFar[i]);61 62 for (final int i : values)63 maxRankSoFar[i] = maxRank + 1;64 }65 for (Pair<Integer, Integer> grid : grids) {66 final int i = grid.getKey();67 final int j = grid.getValue();68 ans[i][j] = maxRankSoFar[i];69 }70 }71 72 return ans;73 }74}75