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
Mr. X and His Shots
A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of M
View Solution →Jim and the Skyscrapers
Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space
View Solution →Palindromic Subsets
Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t
View Solution →Counting On a Tree
Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n
View Solution →Polynomial Division
Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie
View Solution →Costly Intervals
Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the
View Solution →