title: 2352. Equal Row and Column Pairs
tags:
- hasht table
categories: leetcode
comments: false
class Solution {
public:
int equalPairs(vector<vector<int>>& grid) {
// 3 1 2 2
// 1 4 4 5
// 2 4 2 2
// 2 4 2 2
// 3 1 2 2
// 1 4 4 4
// 2 4 2 2
// 2 5 2 2
int n = grid.size(), count=0;
vector<vector<int>> rows, cols(n,vector<int>(n,0));
for(int i=0;i<n;++i) rows.push_back(grid[i]);
for(int j=0;j<n;++j){
for(int i=0;i<n;++i){
cols[j][i] = grid[i][j];
}
}
for(int i=0;i<n;++i){
for(int j=0;j<n;++j){
// check
bool isSame = true;
for(int k=0;k<n;++k){
if(rows[i][k]!=cols[j][k]){
isSame = false;
break;
}
}
if(isSame) count++;
}
}
return count;
}
};
class Solution {
public:
int equalPairs(vector<vector<int>>& grid) {
// 3 1 2 2
// 1 4 4 5
// 2 4 2 2
// 2 4 2 2
// 3 1 2 2
// 1 4 4 4
// 2 4 2 2
// 2 5 2 2
int n = grid.size(), count=0;
map<vector<int>, int> rows, cols;
for(int j=0;j<n;++j){
rows[grid[j]]++;
vector<int> tmp;
for(int i=0;i<n;++i) tmp.push_back(grid[i][j]);
cols[tmp]++;
}
for(auto r:rows){
if(cols.count(r.first)){
count+=cols[r.first]*r.second;
}
}
return count;
}
};
- time complexity
O(n^3)
-> O(n^2)
- space complexity
O(n*n)