Problem

Qn - Equal Row and Column Pairs

Approach

Pretty straightforward, just use space to store the columns and iterate through the rows to find the matching columns

Complexity

  • Time:
  • Space:

Code

class Solution:
    def equalPairs(self, grid: List[List[int]]) -> int:
        colsData = defaultdict(int)
        rows, cols = len(grid), len(grid[0])
        result = 0
 
        # populate the cols data
        for c in range(cols):
            col = []
            for r in range(rows): col.append(grid[r][c])
            colsData[tuple(col)] += 1
 
        # iterate through the rows and find pairs
        for r in range(rows):
            if tuple(grid[r]) in colsData: result += colsData[tuple(grid[r])]
 
        return result