2352. Equal Row and Column Pairs
Problem
In the n×n matrix grid, count the pairs (row r, column c) where row r and column c contain the same values in the same order.
Example: [[3,2,1],[1,7,6],[2,7,7]] → 1 (row 2 equals column 1)
Constraints: n ≤ 200.
Hash every row as a tuple and count; then for each column (as a tuple) add how many rows equal it.
Complexity: O(n²).
class Solution:
def equalPairs(self, grid: List[List[int]]) -> int:
rows = Counter(tuple(r) for r in grid)
return sum(rows[col] for col in zip(*grid))
assert Solution().equalPairs([[3, 2, 1], [1, 7, 6], [2, 7, 7]]) == 1
assert Solution().equalPairs([[3, 1, 2, 2], [1, 4, 4, 5], [2, 4, 2, 2], [2, 4, 2, 2]]) == 3
assert Solution().equalPairs([[1]]) == 1
class Solution {
public int equalPairs(int[][] grid) {
int n = grid.length, res = 0;
Map<String, Integer> rows = new HashMap<>();
for (int[] r : grid) rows.merge(Arrays.toString(r), 1, Integer::sum);
for (int c = 0; c < n; c++) {
int[] col = new int[n];
for (int r = 0; r < n; r++) col[r] = grid[r][c];
res += rows.getOrDefault(Arrays.toString(col), 0);
}
return res;
}
}
func equalPairs(grid [][]int) int {
n := len(grid)
rows := map[string]int{}
for _, r := range grid {
rows[fmt.Sprint(r)]++
}
res := 0
for c := 0; c < n; c++ {
col := make([]int, n)
for r := 0; r < n; r++ {
col[r] = grid[r][c]
}
res += rows[fmt.Sprint(col)]
}
return res
}