Problem solution · C++

Rank Transform of a Matrix

Rank Transform of a Matrix: a C++ 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
65 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

  • 65 lines of C++ from the credited upstream file 1632.cpp.
  • 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 · C++C++
Use this to learn the idea, then write your own version.
class UnionFind { public:  void union_(int u, int v) {    if (!id.contains(u))      id[u] = u;    if (!id.contains(v))      id[v] = v;    const int i = find(u);    const int j = find(v);    if (i != j)      id[i] = j;  }   unordered_map<int, vector<int>> getGroupIdToValues() {    unordered_map<int, vector<int>> groupIdToValues;    for (const auto& [u, _] : id)      groupIdToValues[find(u)].push_back(u);    return groupIdToValues;  }  private:  unordered_map<int, int> id;   int find(int u) {    return id[u] == u ? u : id[u] = find(id[u]);  }}; class Solution { public:  vector<vector<int>> matrixRankTransform(vector<vector<int>>& matrix) {    const int m = matrix.size();    const int n = matrix[0].size();    vector<vector<int>> ans(m, vector<int>(n));    // {val: [(i, j)]}    map<int, vector<pair<int, int>>> valToGrids;    // rank[i] := the maximum rank of the row or column so far    vector<int> maxRankSoFar(m + n);     for (int i = 0; i < m; ++i)      for (int j = 0; j < n; ++j)        valToGrids[matrix[i][j]].emplace_back(i, j);     for (const auto& [val, grids] : valToGrids) {      UnionFind uf;      for (const auto& [i, j] : grids)        // Union i-th row with j-th col.        uf.union_(i, j + m);      for (const auto& [groupId, values] : uf.getGroupIdToValues()) {        // Get the maximum rank of all the included rows and columns.        int maxRank = 0;        for (const int i : values)          maxRank = max(maxRank, maxRankSoFar[i]);        // Update all the rows and columns to maxRank + 1.        for (const int i : values)          maxRankSoFar[i] = maxRank + 1;      }      for (const auto& [i, j] : grids)        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 ↗