MediumNo. 2352
Equal Row and Column Pairs — LeetCode 2352 Python Solution
- Pattern
- Matrix and Grid
- Topics
- Array, Hash Table, Matrix, Simulation
- On a study list
- LeetCode 75
- 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
- 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
| No. | Problem | Difficulty |
|---|---|---|
| 1275 | Find Winner on a Tic Tac Toe Game | Easy |
| 2357 | Make Array Zero by Subtracting Equal Amounts | Easy |
| 0036 | Valid Sudoku | Medium |
| 0037 | Sudoku Solver | Hard |
| 0073 | Set Matrix Zeroes | Medium |
| 0840 | Magic Squares In Grid | Medium |
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.