Dare2Solve
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.
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.
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.
O(N^2), as we may need additional space to store the rows and columns as strings or sequences for comparison.
class Solution {
public:
int equalPairs(vector<vector<int>>& 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;
}
};
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
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;
}
}
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
};