Problem
Given a 0-indexed n x n
integer matrix grid
, return the number of pairs (ri, cj)
such that row ri
and column cj
are equal.
A row and column pair is considered equal if they contain the same elements in the same order (i.e., an equal array).
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
n == grid.length == grid[i].length
1 <= n <= 200
1 <= grid[i][j] <= 105
Solution
Method 1 – Hash Map for Row and Column Serialization
Intuition
The key idea is to serialize each row and column into a tuple or string, so we can easily compare them. By counting the frequency of each row’s serialization, we can efficiently check how many columns match any row by comparing their serialization.
Approach
- Serialize each row of
grid
into a tuple and count its frequency using a hash map. - For each column, serialize it into a tuple and check how many times it appears in the row hash map.
- Sum up the counts for all columns to get the total number of equal row and column pairs.
Complexity
- ⏰ Time complexity:
O(n^2)
, wheren
is the size of the grid, since we process all rows and columns. - 🧺 Space complexity:
O(n^2)
, for storing serialized rows in the hash map.
Code
|
|
|
|
|
|