Equal Row and Column Pairs (LeetCode 2352): Solution and Explanation
Count the pairs (row, column) in an n x n grid where the row, read left to right, is the same sequence as the column read top to bottom. Store every row in a hash map with its frequency, then each column needs one lookup.
Intuition
The direct approach compares each of the n rows with each of the n columns, element by element. That is n^2 pairs times n comparisons, O(n^3).
Equality of two sequences is exactly what a hash map is good at. If each row becomes a key, such as a tuple, then asking "is there a row equal to this column?" is a single lookup.
Rows can repeat. When two rows are identical, a column that matches one of them matches both, so the map stores a count per key and each column adds that count.
Approach: Row frequency map
- Create an empty map
rowsfrom row key to count. - For each row, build
key = tuple(row)and incrementrows[key]. - For each column
c, build the tuple(grid[0][c], grid[1][c], ..., grid[n-1][c]). - Add
rows.get(column_key, 0)tocount, then returncount.
Step-by-step example
grid = [[3,2,1],[1,7,6],[2,7,7]]
- Store the rows: (3,2,1) -> 1, (1,7,6) -> 1, (2,7,7) -> 1.
- Column 0 is (3,1,2). It is not a key, so count stays 0.
- Column 1 is (2,7,7). It matches row 2, so count becomes 1.
- Column 2 is (1,6,7). It is not a key. The answer is 1.
Code: Python, Java, C++
1class Solution:
2 def equalPairs(self, grid: List[List[int]]) -> int:
3 n = len(grid)
4 rows = {}
5 for row in grid:
6 key = tuple(row)
7 rows[key] = rows.get(key, 0) + 1
8 count = 0
9 for c in range(n):
10 col = tuple(grid[r][c] for r in range(n))
11 count += rows.get(col, 0)
12 return count1class Solution {
2 public int equalPairs(int[][] grid) {
3 int n = grid.length;
4 Map<String, Integer> rows = new HashMap<>();
5 for (int[] row : grid) {
6 String key = Arrays.toString(row);
7 rows.put(key, rows.getOrDefault(key, 0) + 1);
8 }
9 int count = 0;
10 for (int c = 0; c < n; c++) {
11 int[] col = new int[n];
12 for (int r = 0; r < n; r++) col[r] = grid[r][c];
13 count += rows.getOrDefault(Arrays.toString(col), 0);
14 }
15 return count;
16 }
17}1class Solution {
2public:
3 int equalPairs(vector<vector<int>>& grid) {
4 int n = grid.size();
5 map<vector<int>, int> rows;
6 for (auto& row : grid) {
7 rows[row]++;
8 }
9 int count = 0;
10 for (int c = 0; c < n; c++) {
11 vector<int> col(n);
12 for (int r = 0; r < n; r++) col[r] = grid[r][c];
13 auto it = rows.find(col);
14 if (it != rows.end()) count += it->second;
15 }
16 return count;
17 }
18};Time and space complexity
O(n^2)
Each of the 2n keys has length n to build and hash, so the total work is proportional to the number of cells.
O(n^2)
The map can hold up to n distinct row keys of length n.
Other approaches
Compare every row with every column (time O(n^3), space O(1))
Two nested loops over rows and columns and an inner loop over k. Simple and needs no extra memory, but it is cubic.
Trie of rows (time O(n^2), space O(n^2))
Insert each row into a trie with a count at the leaf, then walk each column down the trie. It avoids building string keys and stops early on a mismatch.
Common mistakes
- Storing rows in a set instead of counting them. Duplicate rows each form their own pair with a matching column.
- Joining numbers without a separator, so [1,23] and [12,3] both become "123".
- Using a Python list as a dictionary key; it is not hashable, so convert it to a tuple.
- Reading the column left to right from a row instead of top to bottom down the grid.
Frequently asked questions
Why does a column add the row count instead of 1?
Each identical row forms a separate pair with that column. If two rows are both [2,4,2,2] and column 2 is also [2,4,2,2], that column contributes two pairs.
Could I transpose the grid first?
Yes. After transposing, columns become rows, and you count how many rows of the original equal rows of the transpose. It is the same idea with an extra copy of the grid.
What is the time and space complexity of Equal Row and Column Pairs?
O(n^2) time with a hash map, since every cell is read a constant number of times, and O(n^2) space for the stored row keys.