**Rank of a Matrix - Google Top Interview Questions**

### Problem Statement :

You are given a two-dimensional list of integers matrix. Return a new matrix A with the same dimensions such that each A[r][c] is the rank of matrix[r][c]. The ranks of any two elements a and b that are either on the same row or column are calculated by: rank(a) < rank(b) if a < b rank(a) > rank(b) if a > b rank(a) = rank(b) if a = b Ranks are greater than or equal to 1 but are as small as possible. Constraints 0 ≤ n, m ≤ 250 where n and m are the number of rows and columns in matrix Example 1 Input matrix = [ [5, 1, 3], [1, 6, 1], [2, 3, 1] ] Output [ [3, 1, 2], [1, 4, 1], [2, 3, 1] ] Example 2 Input matrix = [ [3, 3], [3, 3] ] Output [ [1, 1], [1, 1] ]

### Solution :

` ````
Solution in C++ :
pair<int, int> find(vector<vector<pair<int, int>>>& parent, pair<int, int> ele) {
auto [x, y] = ele;
if (parent[x][y] == ele) return ele;
return parent[x][y] = find(parent, parent[x][y]);
}
// this function does the union of two elements who have same value and share either the row or
// column.
void unio(vector<vector<pair<int, int>>>& parent, pair<int, int>& a, pair<int, int> b) {
auto [x1, y1] = find(parent, a);
auto [x2, y2] = find(parent, b);
if (x1 == x2 and y1 == y2) {
return;
}
parent[x1][y1] = {x2, y2};
}
vector<vector<int>> solve(vector<vector<int>>& nums) {
int n = nums.size(), m = nums[0].size();
// here we create a parent array with each element pointing to itself.
vector<vector<pair<int, int>>> parent(n, vector<pair<int, int>>(m));
// for keeping the highest rank's in rows and columns.
vector<int> row(n, 0), col(m, 0);
// initializing the dsu
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
parent[i][j] = {i, j};
}
}
// union all the element which share the common row and have equal values.
for (int i = 0; i < n; i++) {
unordered_map<int, pair<int, int>> rows;
for (int j = 0; j < m; j++) {
if (rows.find(nums[i][j]) != rows.end()) {
unio(parent, rows[nums[i][j]], {i, j});
}
rows[nums[i][j]] = {i, j};
}
}
// union all the element which share the common columns and have equal values
for (int j = 0; j < m; j++) {
unordered_map<int, pair<int, int>> cols;
for (int i = 0; i < n; i++) {
if (cols.find(nums[i][j]) != cols.end()) {
unio(parent, cols[nums[i][j]], {i, j});
}
cols[nums[i][j]] = {i, j};
}
}
// now let's make the actual parent mapping. means all the element point to their real parents.
vector<vector<pair<int, int>>> parentmapping(n, vector<pair<int, int>>(m));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
parentmapping[i][j] = find(parent, {i, j});
}
}
// now let's make the reverse parent mapping where all the elements which are in a connected
// component can be identified.
map<pair<int, int>, vector<pair<int, int>>> rev_mapping;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
rev_mapping[parentmapping[i][j]].push_back({i, j});
}
}
// so far all the job done for finding the connected component's
// now we start picking the element from the smaller values so we put them in a temporary array
// and start picking the smaller values first.
vector<vector<int>> temp;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
temp.push_back({nums[i][j], i, j});
}
}
sort(temp.begin(), temp.end());
// this is the array we return
vector<vector<int>> ret(n, vector<int>(m, 0));
// let's start giving the ranks.
vector<vector<int>> visited(n, vector<int>(m, 0));
for (int i = 0; i < temp.size(); i++) {
int vals = temp[i][0], x = temp[i][1], y = temp[i][2];
// if this element has been already ranked we skip the element.
if (visited[x][y] == 1) continue;
// now we find the max rank that has been given to the elements which share the common rows
// and colums to the elements of the connected componenets.
int max_rank_so_far = 0;
pair<int, int> its_parent = parentmapping[x][y];
for (auto& nbrs : rev_mapping[its_parent]) {
max_rank_so_far = max({max_rank_so_far, row[nbrs.first], col[nbrs.second]});
}
// we give the {final rank} as {max rank + 1}.
int f_rank = max_rank_so_far + 1;
// here we give the ranks to the elements and marked them as visited.
for (auto [p, q] : rev_mapping[its_parent]) {
visited[p][q] = 1;
row[p] = col[q] = ret[p][q] = f_rank;
}
}
return ret;
}
```

` ````
Solution in Python :
class UnionFind:
def __init__(self):
self._parent = {}
self._size = {}
self._max_rank = {}
def union(self, a, b, rank):
a, b = self.find(a), self.find(b)
if a == b:
return
if self._size[a] < self._size[b]:
a, b = b, a
self._parent[b] = a
self._size[a] += self._size[b]
self._max_rank[a] = max(self._max_rank[a], self._max_rank[b], rank)
def find(self, x):
if x not in self._parent:
self._parent[x] = x
self._size[x] = 1
self._max_rank[x] = 0
return x
while self._parent[x] != x:
self._parent[x] = self._parent[self._parent[x]]
x = self._parent[x]
return x
def max_rank(self, x):
return self._max_rank[self.find(x)]
class Solution:
def solve(self, matrix):
if not matrix or not matrix[0]:
return matrix
m, n = len(matrix), len(matrix[0])
groups = defaultdict(list)
for y, row in enumerate(matrix):
for x, val in enumerate(row):
groups[val].append((y, x))
A = [[0] * n for _ in range(m)]
row_rank = [0] * m
col_rank = [0] * n
for val in sorted(groups):
uf = UnionFind()
for y, x in groups[val]:
uf.union(y, ~x, max(row_rank[y], col_rank[x]))
for y, x in groups[val]:
A[y][x] = row_rank[y] = col_rank[x] = uf.max_rank(y) + 1
return A
```

## View More Similar Problems

## Lazy White Falcon

White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi

View Solution →## Ticket to Ride

Simon received the board game Ticket to Ride as a birthday present. After playing it with his friends, he decides to come up with a strategy for the game. There are n cities on the map and n - 1 road plans. Each road plan consists of the following: Two cities which can be directly connected by a road. The length of the proposed road. The entire road plan is designed in such a way that if o

View Solution →## Heavy Light White Falcon

Our lazy white falcon finally decided to learn heavy-light decomposition. Her teacher gave an assignment for her to practice this new technique. Please help her by solving this problem. You are given a tree with N nodes and each node's value is initially 0. The problem asks you to operate the following two types of queries: "1 u x" assign x to the value of the node . "2 u v" print the maxim

View Solution →## Number Game on a Tree

Andy and Lily love playing games with numbers and trees. Today they have a tree consisting of n nodes and n -1 edges. Each edge i has an integer weight, wi. Before the game starts, Andy chooses an unordered pair of distinct nodes, ( u , v ), and uses all the edge weights present on the unique path from node u to node v to construct a list of numbers. For example, in the diagram below, Andy

View Solution →## Heavy Light 2 White Falcon

White Falcon was amazed by what she can do with heavy-light decomposition on trees. As a resut, she wants to improve her expertise on heavy-light decomposition. Her teacher gave her an another assignment which requires path updates. As always, White Falcon needs your help with the assignment. You are given a tree with N nodes and each node's value Vi is initially 0. Let's denote the path fr

View Solution →## Library Query

A giant library has just been inaugurated this week. It can be modeled as a sequence of N consecutive shelves with each shelf having some number of books. Now, being the geek that you are, you thought of the following two queries which can be performed on these shelves. Change the number of books in one of the shelves. Obtain the number of books on the shelf having the kth rank within the ra

View Solution →