Equal Row and Column Pairs (LeetCode 2352): Solution and Explanation

Medium
Array
Hash Table
Matrix
Simulation

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

  1. Create an empty map rows from row key to count.
  2. For each row, build key = tuple(row) and increment rows[key].
  3. For each column c, build the tuple (grid[0][c], grid[1][c], ..., grid[n-1][c]).
  4. Add rows.get(column_key, 0) to count, then return count.

Step-by-step example

grid = [[3,2,1],[1,7,6],[2,7,7]]
  1. Store the rows: (3,2,1) -> 1, (1,7,6) -> 1, (2,7,7) -> 1.
  2. Column 0 is (3,1,2). It is not a key, so count stays 0.
  3. Column 1 is (2,7,7). It matches row 2, so count becomes 1.
  4. 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 count
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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.

Space

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.