MediumNo. 2352

Equal Row and Column Pairs — LeetCode 2352 Python Solution

Topics
Array, Hash Table, Matrix, Simulation
On a study list
LeetCode 75
Reading time
2 min

The problem

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

Input
grid = [[3,2,1],[1,7,6],[2,7,7]]
Output
1
Explanation
There is 1 equal row and column pair:

Python solution

PythonSolution
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):
                ans += all(grid[i][k] == grid[k][j] for k in range(n))
        return ans

Complexity

Time
O(n3)where n is the number of rows or columns in the matrix grid
Space · auxiliary
O(1)

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 2352. Equal Row and Column Pairs is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2352. Equal Row and Column Pairs?

LeetCode 2352. Equal Row and Column Pairs is rated Medium on LeetCode.

What topics does LeetCode 2352. Equal Row and Column Pairs cover?

LeetCode 2352. Equal Row and Column Pairs is tagged Array, Hash Table, Matrix and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.