Sponsored
Sponsored
The straightforward way to solve the problem is by iteratively comparing each row with every column to determine if they are equal. This approach requires looping through each pair of row and column and verifying the elements one by one.
Time Complexity: O(n^3), as it involves comparing elements for each pair. Space Complexity: O(1), since no extra data structures are used except for counters.
1def equal_pairs(grid):
2 n = len(grid)
3 count = 0
4 for i in range(n):
5 for j in range(n):
6 if all(grid[i][k] == grid[k][j] for k in range(n)):
7 count += 1
8 return count
9
10grid = [[3, 2, 1], [1, 7, 6], [2, 7, 7]]
11print(equal_pairs(grid))
The Python code uses list comprehension to check equality of rows and columns within nested loops, producing the count of equal pairs if elements match one to one.
By converting rows and columns into hashable objects (such as tuples in Python or strings in other languages), we can store their occurrences in a dictionary or a hash map. This facilitates a more efficient comparison by checking the presence of corresponding row and column hashes in the stored data structure.
Time Complexity: O(n^2) for transposing and additional O(n^3) for comparisons. Space Complexity: O(n^2) for storing the transposed matrix.
1#include <vector>
#include <unordered_map>
using namespace std;
typedef vector<int> vi;
int equalPairs(vector<vi>& grid) {
int n = grid.size();
unordered_map<string, int> rowMap;
for (int i = 0; i < n; ++i) {
string key = "";
for (int j = 0; j < n; ++j) {
key += to_string(grid[i][j]) + ",";
}
rowMap[key]++;
}
int count = 0;
for (int j = 0; j < n; ++j) {
string key = "";
for (int i = 0; i < n; ++i) {
key += to_string(grid[i][j]) + ",";
}
if (rowMap.count(key)) {
count += rowMap[key];
}
}
return count;
}
int main() {
vector<vector<int>> grid = {{3, 2, 1}, {1, 7, 6}, {2, 7, 7}};
cout << equalPairs(grid) << endl;
return 0;
}
Using unordered_map for hashing rows, this solution stores rows as hash keys and then checks columns against these keys. Each column conversion matches stored keys to count equal pairs.