Problem Statement
leetcode problem link
My Solution [Accepted]
public class Solution {
public Dictionary<int, int[]> ColDict {set;get;}
public Dictionary<int, int[]> RowDict {set;get;}
public bool IsValid(int col, int row, int[][] grid) {
int[] colItems = ColDict[col];
int[] rowItems = RowDict[row];
return colItems.SequenceEqual(rowItems);
}
public int EqualPairs(int[][] grid) {
var n = grid.Length;
var res = 0;
ColDict = new Dictionary<int, int[]>();
RowDict = new Dictionary<int, int[]>();
for(int i = 0; i < n; i++) {
ColDict.Add(i, grid[i].Select(x => x).ToArray());
}
for(int j = 0; j < n; j++) {
int[] temp = new int[n];
for (int i = 0; i < n; i++) {
temp[i] = grid[i][j];
}
RowDict.Add(j, temp.Select(x => x).ToArray());
}
for(int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (IsValid(i, j, grid)) {
res++;
}
}
}
return res;
}
}
Improved Code
public class Solution {
public int EqualPairs(int[][] grid) {
int n = grid.Length;
var rowCount = new Dictionary<string, int>();
// Convert each row to a string key and count occurrences
for (int i = 0; i < n; i++) {
string key = string.Join(",", grid[i]);
if (!rowCount.ContainsKey(key))
rowCount[key] = 0;
rowCount[key]++;
}
int result = 0;
// Build each column and check if it matches any row
for (int col = 0; col < n; col++) {
int[] colArr = new int[n];
for (int row = 0; row < n; row++)
colArr[row] = grid[row][col];
string colKey = string.Join(",", colArr);
if (rowCount.ContainsKey(colKey))
result += rowCount[colKey];
}
return result;
}
}
Editorial
Approach 2: Hash Map
class Solution:
def equalPairs(self, grid: List[List[int]]) -> int:
count = 0
n = len(grid)
# Keep track of the frequency of each row.
row_counter = collections.Counter(tuple(row) for row in grid)
# Add up the frequency of each column in map.
for c in range(n):
col = [grid[i][c] for i in range(n)]
count += row_counter[tuple(col)]
return count