Skip to content

2352. Equal Row and Column Pairs 👍

  • Time: $O(n^3)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int equalPairs(vector<vector<int>>& grid) {
    const int n = grid.size();
    int ans = 0;

    for (int i = 0; i < n; ++i)
      for (int j = 0; j < n; ++j) {
        int k = 0;
        for (; k < n; ++k)
          if (grid[i][k] != grid[k][j])
            break;
        if (k == n)  // R[i] == C[j]
          ++ans;
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int equalPairs(int[][] grid) {
    final int n = grid.length;
    int ans = 0;

    for (int i = 0; i < n; ++i)
      for (int j = 0; j < n; ++j) {
        int k = 0;
        for (; k < n; ++k)
          if (grid[i][k] != grid[k][j])
            break;
        if (k == n) // R[i] == C[j]
          ++ans;
      }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def equalPairs(self, grid: list[list[int]]) -> int:
    n = len(grid)
    ans = 0

    for i in range(n):
      for j in range(n):
        k = 0
        while k < n:
          if grid[i][k] != grid[k][j]:
            break
          k += 1
        if k == n:  # R[i] == C[j]
          ans += 1

    return ans