Equal Row and Column Pairs — LeetCode 2352 Python Solution
- Problem
- #2352
- Pattern
- Matrix and Grid
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^3), where n is the number of rows or columns in the matrix grid |
| Space | O(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.