InterviewPrepKit

Home / Coding / Arrays & Hashing

Equal Row and Column Pairs

medium Original ↗
Solving tips
  • Turn element-by-element comparison into a hash lookup: count tuple(row) in a Counter, then for each column add the counter's value for that column tuple.
  • Use zip(*grid) to transpose and get columns as tuples in one expression.
  • Freeze rows/columns to tuples (lists aren't hashable, and list != tuple in Python is a silent bug).
  • Store multiplicities not a set, so duplicate rows matching a column count each pair; target O(n^2) time and space vs the O(n^3) brute force.

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 — passable here, but the intended hash-based solution is O(n²), and the gap widens fast as n grows.

Think about it first

Hint 1 A row and a column match only if they're the same *sequence*. Could you count matches faster if you could test "is this column equal to any row?" in one shot instead of n comparisons?
Hint 2 Hash the rows: a dict from row-content → how many rows look like that. What must you convert each row into before it can be 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.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.