#2352
Equal Row and Column Pairs
MediumArrayHash TableMatrixSimulationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
Instead of comparing each row with each column directly, we can use a HashMap to store the frequency of each row. Then, we can check how many columns match these rows using the same HashMap, which significantly reduces the number of comparisons.
⚙️
Algorithm
3 steps- 1Step 1: Create a HashMap to count occurrences of each row as a string.
- 2Step 2: For each column, convert it to a string and check if it exists in the HashMap.
- 3Step 3: Sum the counts from the HashMap for matching columns.
solution.py10 lines
1from collections import Counter
2
3def equalPairs(grid):
4 n = len(grid)
5 row_count = Counter(tuple(row) for row in grid)
6 count = 0
7 for c in range(n):
8 column = tuple(grid[r][c] for r in range(n))
9 count += row_count[column]
10 return countℹ
Complexity note: The time complexity remains O(n²) due to the need to process each element in the grid. However, we use O(n) space for the HashMap to store row frequencies, which allows us to quickly check for matching columns.
- 1Using a HashMap can significantly reduce the number of comparisons needed.
- 2String representations of rows and columns simplify equality checks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.