Problem
Given an n x n integer matrix grid, return the number of pairs(ri, cj) such that the i-th row and j-th column are equal.
A row and column form a pair when they contain the same elements in the same order.
Example(s)
Consider the following examples to understand the expected input and output.Example 1
Input
grid = [[3,2,1],
[1,7,6],
[2,7,7]]
Output
1
Example 2
Input
grid = [[1,1,1],
[1,1,1],
[1,1,1]]
Output
9
Solution
There are two approaches to solve this problem. The first approach directly compares every row with every column, while the second approach uses a HashMap to efficiently match rows and columns.Approach 1: Brute Force
In this approach, we consider every possible row-column pair. For each row and column, we compare their elements one by one.The
isEqual() method compares the elements of the selected row and column. If every corresponding element is equal, the row-column pair is counted.
class Solution {
public int equalPairs(int[][] grid) {
int n = grid.length;
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (isEqual(i, j, grid)) {
count++;
}
}
}
return count;
}
private boolean isEqual(int row, int column, int[][] grid) {
for (int i = 0; i < grid.length; i++) {
if (grid[row][i] != grid[i][column]) {
return false;
}
}
return true;
}
}
Complexity
There aren2 possible row-column pairs, and comparing one pair takes O(n) time. Therefore, the time complexity is O(n3).
The solution uses only a constant amount of extra space, so the space complexity is
O(1).
Approach 2: HashMap
We can optimize the solution by storing every row in a HashMap along with its frequency.For each row, we convert the row into a string using
Arrays.toString() and use it as the key in the map. If the same row appears multiple times, its frequency is increased.
We then construct each column as an array and convert it into a string using the same representation. If the column representation exists in the HashMap, its frequency is added to the result.
This approach also handles duplicate rows correctly because the map stores the frequency of each unique row.
class Solution {
public int equalPairs(int[][] grid) {
Map<String, Integer> map = new HashMap<>();
int n = grid.length;
int count = 0;
// Store row frequencies
for (int i = 0; i < n; i++) {
String key = Arrays.toString(grid[i]);
map.put(key, map.getOrDefault(key, 0) + 1);
}
// Match columns with rows
for (int i = 0; i < n; i++) {
int[] column = new int[n];
for (int j = 0; j < n; j++) {
column[j] = grid[j][i];
}
String key = Arrays.toString(column);
count += map.getOrDefault(key, 0);
}
return count;
}
}
Complexity
We process every element while constructing the row and column representations, resulting in a time complexity ofO(n2).
The HashMap stores up to
n row representations, with each representation containing n elements. Therefore, the extra space complexity is O(n2).
Comments
No comments yet. Ask a question or share what helped.