Статья пока доступна только на английском.
Problem Description
You are given an n x n matrix grid of positive integers.
Count the number of pairs (ri, cj) such that row ri
equals column cj.
A row and a column are considered equal if they contain the same elements in the same order.
Constraints
nis in the range from 1 to 200- Each matrix element is in the range from 1 to 105
Examples
Input: grid = [[3,2,1],[1,7,6],[2,7,7]]
Answer: 1
There is one equal pair:
- (Row 2, Column 1):
[2,7,7]
Solution
To solve the problem, we need to count the pairs of rows and columns in the matrix that match. We do this in two passes: one over the rows and one over the columns.
Build a row count map:
- Initialize an empty hash table (an object in TypeScript)
countMapthat stores rows as keys and their counts as values. - Go over each row of the matrix. For each row, build a string key by concatenating all its elements separated by semicolons.
- If the key already exists in
countMap, increment its value by one. Otherwise, set the value to one.
Count matching columns:
- Initialize a counter
counterthat stores the total number of matching pairs. - Go over each column of the matrix. For each column, build a string key by concatenating its elements in order, separated by semicolons.
- If the key exists in
countMap, add its value fromcountMaptocounter.
After processing all columns, return counter, which equals the number of matching row and column pairs.
export const equalPairs = (grid: number[][]): number => {
const countMap: Record<string, number> = {};
let counter = 0;
grid.forEach((row) => {
let key = '';
row.forEach((col) => {
key = `${key}${col};`;
});
if (countMap[key]) {
countMap[key]++;
} else {
countMap[key] = 1;
}
});
for (let j = 0; j < grid.length; j++) {
let key = '';
for (let i = 0; i < grid.length; i++) {
key = `${key}${grid[i][j]};`;
}
if (countMap[key]) {
counter += countMap[key];
}
}
return counter;
};Complexity Analysis
Time Complexity
The solution has O(n2) time complexity, since we traverse the whole matrix twice.
Space Complexity
The space complexity is O(n), since we create a hash table keyed by unique rows.
In the worst case, its size is n if all rows of the matrix are unique.