Equal Row and Column Pairs — LeetCode 2352 Python Solution

MediumArrayHash TableMatrixSimulation
Problem
#2352
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

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

Complexity

MeasureComplexity
TimeO(n^3), where n is the number of rows or columns in the matrix grid
SpaceO(1) auxiliary

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

On a study list

This problem is on LeetCode 75.

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.

Get Stealth Interview