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
By transposing the matrix first, each row in the original matrix can be compared directly with the columns of the transposed matrix. A helper function is used to compare arrays element by element.