🎨Now live: Try our Free AI Image Generation Feature

Description
Given a 2D grid of integers, the task is to find the number of pairs of rows and columns that are identical. A pair is considered identical if the sequence of elements in the row matches exactly with the sequence of elements in the column.
Intuition
The problem can be thought of as comparing each row with each column to check if they are the same. By treating each row and each column as a string or sequence, we can easily compare them to find identical pairs.
Approach
- Iterate through each row of the grid.
- Convert the row into a string or sequence format that can be compared.
- For each row, iterate through all columns, and convert the column into a comparable format.
- Compare the row with each column, and if they match, count it as an identical pair.
- Return the total number of identical pairs.
Complexity
Time Complexity:
O(N^3), where N is the size of the grid. This is because for each row, we iterate through each column, and converting a column into a string or sequence takes O(N) time.
Space Complexity:
O(N^2), as we may need additional space to store the rows and columns as strings or sequences for comparison.
Code
C++
class Solution {
public:
int equalPairs(vector>& grid) {
int res = 0;
int n = grid.size();
for (int i = 0; i < n; ++i) {
string row;
for (int k = 0; k < n; ++k) {
row += to_string(grid[i][k]) + ",";
}
for (int j = 0; j < n; ++j) {
string col;
for (int k = 0; k < n; ++k) {
col += to_string(grid[k][j]) + ",";
}
if (col == row) {
res++;
}
}
}
return res;
}
};
Python
class Solution:
def equalPairs(self, grid: List[List[int]]) -> int:
res = 0
n = len(grid)
for i in range(n):
row = ','.join(map(str, grid[i]))
for j in range(n):
col = ','.join(str(grid[k][j]) for k in range(n))
if col == row:
res += 1
return res
Java
class Solution {
public int equalPairs(int[][] grid) {
int res = 0;
int n = grid.length;
for (int i = 0; i < n; ++i) {
StringBuilder row = new StringBuilder();
for (int k = 0; k < n; ++k) {
row.append(grid[i][k]).append(",");
}
for (int j = 0; j < n; ++j) {
StringBuilder col = new StringBuilder();
for (int k = 0; k < n; ++k) {
col.append(grid[k][j]).append(",");
}
if (col.toString().equals(row.toString())) {
res++;
}
}
}
return res;
}
}
JavaScript
var equalPairs = function (grid) {
let res = 0
for (let i = 0; i < grid.length; ++i) {
let row = grid[i].join()
for (let j = 0; j < grid.length; ++j) {
let col = grid.map((v) => v[j]).join()
if (col == row) {
res++
}
}
}
return res
};