Equal Row and Column Pairs - 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).

Input & Output

Example 1 — Basic Case
$ Input: grid = [[3,2,1],[1,7,1],[5,7,1]]
Output: 0
💡 Note: We check all row-column pairs: Row 0 [3,2,1] vs Columns [3,1,5], [2,7,7], [1,1,1] - no matches. Row 1 [1,7,1] vs Columns - no matches. Row 2 [5,7,1] vs Columns - no matches. Total: 0 pairs.
Example 2 — Multiple Matches
$ Input: grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]
Output: 3
💡 Note: After checking all row-column pairs systematically, we find 3 pairs where the row pattern exactly matches the column pattern.
Example 3 — Single Element
$ Input: grid = [[5]]
Output: 1
💡 Note: Only one row [5] and one column [5], they are equal, so 1 pair.

Constraints

  • n == grid.length == grid[i].length
  • 1 ≤ n ≤ 200
  • 1 ≤ grid[i][j] ≤ 105

Visualization

Tap to expand
Equal Row and Column Pairs INPUT n x n Matrix Grid r0 r1 r2 c0 c1 c2 3 2 1 1 7 1 5 7 1 Input Values: grid = [[3,2,1], [1,7,1], [5,7,1]] Row 2: [5,7,1] Column 1: [2,7,7] ALGORITHM (Hash) 1 Hash each row Convert rows to strings "3,2,1" --> count: 1 "1,7,1" --> count: 1 "5,7,1" --> count: 1 2 Extract columns Read elements vertically c0: [3,1,5] --> "3,1,5" c1: [2,7,7] --> "2,7,7" 3 Check column 2 c2: [1,1,1] --> "1,1,1" 4 Match found! No column matches row hashes Wait - recheck c2: c2: [1,1,1] vs rows... No match in hash map FINAL RESULT Matching Pairs Found: Pair (r2, c2): Row 2: 5 7 1 Col 2: 1 1 1 Actually checking all pairs: Row 2 = [5,7,1] Col 1 = [2,7,7] Found 1 matching pair Output: 1 OK - 1 equal pair found (row 2, column 2) Key Insight: Using a hash map to store row patterns allows O(1) lookup when checking columns. Convert each row to a string key (e.g., "3,2,1") and count occurrences. Then for each column, create its string and check if it exists in the hash map. TutorialsPoint - Equal Row and Column Pairs | Hash Approach Time: O(n^2) | Space: O(n^2)
Asked in
Amazon 15 Microsoft 12
25.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen