Skip to main content
Back to problems
#2352
Medium Algorithms

Equal row and column pairs

Array Hash Table Matrix Simulation
70.8% acceptance
Feb 25, 2026
2484
192
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).

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
use std::collections::HashMap;


impl Solution {
  pub fn equal_pairs(grid: Vec<Vec<i32>>) -> i32 {
    let n = grid.len();
    let mut row_count: HashMap<Vec<i32>, i32> = HashMap::new();
    for row in &grid {
      *row_count.entry(row.clone()).or_insert(0) += 1;
    }
    let mut ans = 0;
    for j in 0..n {
      let col: Vec<i32> = (0..n).map(|i| grid[i][j]).collect();
      ans += *row_count.get(&col).unwrap_or(&0);
    }
    ans
  }
}