Hash Map / Set· 25 min

Equal Row and Column Pairs

LeetCode #2352 · Medium · Interactive step-by-step visualization

Setup

Example inputgrid = [[3,2,1],[1,7,6],[2,7,7]]
Step 1 / 10

Current step

1 / 10

Hash row 0. Equal rows collapse onto one serialized key, and the count keeps duplicates. [3,2,1] now has count 1.

Step log

Persistent grid

3
2
1
1
7
6
2
7
7

rowKey

[3,2,1]

storedRows

1

pairs

0

Active cursor
Comparing
Best or completed
Leaving or removed
equal-row-and-column-pairs.java
1public int equalPairs(int[][] grid) {
2 Map<String, Integer> rows = new HashMap<>();
3 for (int[] row : grid)
4 rows.merge(Arrays.toString(row), 1, Integer::sum);
5 int pairs = 0;
6 for (int col = 0; col < grid.length; col++) {
7 int[] column = new int[grid.length];
8 for (int row = 0; row < grid.length; row++) column[row] = grid[row][col];
9 pairs += rows.getOrDefault(Arrays.toString(column), 0);
10 }
11 return pairs;
12}
● Java
Time
O(n²)
Space
O(n²)
Pattern
hashing
Frames
10