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.
1
The JavaScript implementation iteratively compares elements of each row to each column using nested loops; it counts pairs where all elements match, increasing the resultant count.
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 <iostream>
2#include <vector>
3#include <unordered_map>
4using namespace std;
5
6typedef vector<int> vi;
7
8int equalPairs(vector<vi>& grid) {
9 int n = grid.size();
10 unordered_map<string, int> rowMap;
11 for (int i = 0; i < n; ++i) {
12 string key = "";
13 for (int j = 0; j < n; ++j) {
14 key += to_string(grid[i][j]) + ",";
15 }
16 rowMap[key]++;
17 }
18 int count = 0;
19 for (int j = 0; j < n; ++j) {
20 string key = "";
21 for (int i = 0; i < n; ++i) {
22 key += to_string(grid[i][j]) + ",";
23 }
24 if (rowMap.count(key)) {
25 count += rowMap[key];
26 }
27 }
28 return count;
29}
30
31int main() {
32 vector<vector<int>> grid = {{3, 2, 1}, {1, 7, 6}, {2, 7, 7}};
33 cout << equalPairs(grid) << endl;
34 return 0;
35}
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.