2352. Equal Row and Column Pairs
1. Description
Given a 0-indexed n x n integer matrix grid, return the number of pairs (ri, cj) such that row ri and column cj are equal.
A row and column pair is considered equal if they contain the same elements in the same order (i.e., an equal array).
2. Example
Example 1:
Input: grid = [[3,2,1],[1,7,6],[2,7,7]]
Output: 1
Explanation: There is 1 equal row and column pair:
- (Row 2, Column 1): [2,7,7]
Example 2:
Input: grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]
Output: 3
Explanation: There are 3 equal row and column pairs:
- (Row 0, Column 0): [3,1,2,2]
- (Row 2, Column 2): [2,4,2,2]
- (Row 3, Column 2): [2,4,2,2]
3. Constraints
- n == grid.length == grid[i].length
- 1 <= n <= 200
- 1 <= grid[i][j] <= $10^5$
4. Solutions
Hash Table
n = grid.size()
Time complexity: O($n^3logn$)
Space complexity: O($n^2$)
I don’t think the time complexity is O(n^2), since searching in a map takes O(log n), and comparing two vectors costs O(n).
class Solution {
public:
int equalPairs(const vector<vector<int>> &grid) {
// Use std::map instead of std::unordered_map
// since std::vector can be used as a key directly.
// Converting the vector to a string would introduce additional overhead
map<vector<int>, int> line_count;
for (auto line : grid) {
++line_count[line];
}
int equal_pairs = 0;
vector<int> column(grid.size());
for (int j = 0; j < grid.front().size(); ++j) {
for (int i = 0; i < grid.size(); ++i) {
column[i] = grid[i][j];
}
equal_pairs += line_count[column];
}
return equal_pairs;
}
};