InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Equal Row and Column Pairs

medium Original ↗ 00:00

Problem

You’re given an n x n integer matrix grid. Count the pairs (r, c) such that row r, read left to right, is element-for-element identical to column c, read top to bottom. Every matching (row index, column index) combination counts, including repeats when duplicate rows or columns match.

Examples

  • grid = [[3, 2, 1], [1, 7, 6], [2, 7, 7]]1 — row 2 is [2, 7, 7] and column 1 is [2, 7, 7]; no other pair matches.
  • grid = [[3, 1, 2, 2], [1, 4, 4, 5], [2, 4, 2, 2], [2, 4, 2, 2]]3 — row 0 matches column 0, and rows 2 and 3 (both [2, 4, 2, 2]) each match column 2.
  • grid = [[5]]1 — the single row equals the single column.

Constraints

  • 1 <= n <= 200
  • 1 <= grid[i][j] <= 10^5

Comparing every row against every column element-by-element is O(n³) ≈ 8·10^6 operations at n = 200. That passes here, but the hash-based solution is O(n²), and the gap grows quickly with n.

Think about it first

Hint 1 A row and a column match only if they are the same sequence. Counting is faster if you can test "does this column equal any row?" in one lookup instead of n separate comparisons.
Hint 2 Hash the rows: a dict from row content to the number of rows with that content. What must you convert each row into before it can serve as a dict key?
Hint 3 Build a `Counter` of `tuple(row)` for all rows, then for each column (hint: `zip` of the rows transposes the grid) add the counter's entry for that column tuple to the answer.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug