2352. Equal Row and Column Pairs LeetCode Solution
In this guide, you will get 2352. Equal Row and Column Pairs LeetCode Solution with the best time and space complexity. The solution to Equal Row and Column Pairs problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Equal Row and Column Pairs solution in C++
- Equal Row and Column Pairs solution in Java
- Equal Row and Column Pairs solution in Python
- Additional Resources

Problem Statement of 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 column pair is considered equal if they contain the same elements in the same order (i.e., an equal array).
Example 1:
Input: grid = [[3,2,1],[1,7,6],[2,7,7]]
Output: 1
Explanation: There is 1 equal row and column pair:
– (Row 2, Column 1): [2,7,7]
Example 2:
Input: grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]
Output: 3
Explanation: There are 3 equal row and column pairs:
– (Row 0, Column 0): [3,1,2,2]
– (Row 2, Column 2): [2,4,2,2]
– (Row 3, Column 2): [2,4,2,2]
Constraints:
n == grid.length == grid[i].length
1 <= n <= 200
1 <= grid[i][j] <= 105
Complexity Analysis
- Time Complexity: O(n^3)
- Space Complexity: O(1)
2352. Equal Row and Column Pairs LeetCode Solution in C++
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;
}
};
/* code provided by PROGIEZ */
2352. Equal Row and Column Pairs LeetCode Solution in Java
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;
}
}
// code provided by PROGIEZ
2352. Equal Row and Column Pairs LeetCode Solution in Python
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
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.