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.
1function equalPairs(grid) {
2 const n = grid.length;
3 let count = 0;
4 for (let i = 0; i < n; i++) {
5 for (let j = 0; j < n; j++) {
6 let isEqual = true;
7 for (let k = 0; k < n; k++) {
8 if (grid[i][k] !== grid[k][j]) {
9 isEqual = false;
10 break;
11 }
12 }
13 if (isEqual) count++;
14 }
15 }
16 return count;
17}
18
19const grid = [[3, 2, 1], [1, 7, 6], [2, 7, 7]];
20console.log(equalPairs(grid));
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
Java solution creates a hash map for rows as keys and then uses these keys to match columns converted to strings, considering multiple matching rows.