Equal Row and Column Pairs

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 a column are equal when they contain the same elements in the same order: `grid[ri][k] == grid[k][cj]` for every `k`.

30:00

Equal Row and Column Pairs
medium
Free written solution
Topics
Companies

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 a column are equal when they contain the same elements in the same order: grid[ri][k] == grid[k][cj] for every k.

Example 1:
Input: {"grid":[[3,2,1],[1,7,6],[2,7,7]]}
Output: 1
Constraints:
  • n==grid.length==grid[i].lengthn == \text{grid.length} == \text{grid}[i].\text{length}

  • 1≤n≤2001 \leq n \leq 200

  • 1≤grid[i][j]≤1051 \leq \text{grid}[i][j] \leq 10^5

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"grid":[[3,2,1],[1,7,6],[2,7,7]]}

Comparing every row with every column would cost n^3 = 27 reads. Instead, store each row as a key in a hash map with how often it occurs, then look each column up.

1. store rows
2. look up columns
count = 0

grid (3 x 3)

c0

c1

c2

r0

3
2
1

r1

1
7
6

r2

2
7
7

rows map: key → count (0 keys)

{ }

A column that matches a key pairs with every row behind that key, so it adds the key's count. Green cells mark (row, column) pairs already counted.

Variables
VariableValue
n3
count0
DepthFunction Call
Stack empty
0/10