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 :



title-img




                        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

Insert a Node at the Tail of a Linked List

You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink

View Solution →

Insert a Node at the head of a Linked List

Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below

View Solution →

Insert a node at a specific position in a linked list

Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e

View Solution →

Delete a Node

Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value. Example: list=0->1->2->3 position=2 After removing the node at position 2, list'= 0->1->-3. Function Description: Complete the deleteNode function in the editor below. deleteNo

View Solution →

Print in Reverse

Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: Sing

View Solution →

Reverse a linked list

Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example: head references the list 1->2->3->Null. Manipulate the next pointers of each node in place and return head, now referencing the head of the list 3->2->1->Null. Function Descriptio

View Solution →