<AI/>
enru
Все статьи

Equal row and column pairs

LeetCode 2352: Count pairs of equal rows and columns in a square matrix using a hash table.

Сложность
Средняя
Опубликовано
Темы
#matrix#hash table
Открыть на LeetCode

Статья пока доступна только на английском.

Problem Description

You are given an n x n matrix grid of positive integers.

Count the number of pairs (ri, cj) such that row ri equals column cj.

A row and a column are considered equal if they contain the same elements in the same order.

Constraints

  • n is in the range from 1 to 200
  • Each matrix element is in the range from 1 to 105

Examples

0 0 1 1 2 2 3 2 1 1 7 6 2 7 7 row 2 = column 1

Input: grid = [[3,2,1],[1,7,6],[2,7,7]]

Answer: 1

There is one equal pair:

  • (Row 2, Column 1): [2,7,7]

Solution

To solve the problem, we need to count the pairs of rows and columns in the matrix that match. We do this in two passes: one over the rows and one over the columns.

Build a row count map:

  • Initialize an empty hash table (an object in TypeScript) countMap that stores rows as keys and their counts as values.
  • Go over each row of the matrix. For each row, build a string key by concatenating all its elements separated by semicolons.
  • If the key already exists in countMap, increment its value by one. Otherwise, set the value to one.

Count matching columns:

  • Initialize a counter counter that stores the total number of matching pairs.
  • Go over each column of the matrix. For each column, build a string key by concatenating its elements in order, separated by semicolons.
  • If the key exists in countMap, add its value from countMap to counter.

After processing all columns, return counter, which equals the number of matching row and column pairs.

typescript
export const equalPairs = (grid: number[][]): number => {
  const countMap: Record<string, number> = {};
  let counter = 0;
 
  grid.forEach((row) => {
    let key = '';
 
    row.forEach((col) => {
      key = `${key}${col};`;
    });
 
    if (countMap[key]) {
      countMap[key]++;
    } else {
      countMap[key] = 1;
    }
  });
 
  for (let j = 0; j < grid.length; j++) {
    let key = '';
 
    for (let i = 0; i < grid.length; i++) {
      key = `${key}${grid[i][j]};`;
    }
 
    if (countMap[key]) {
      counter += countMap[key];
    }
  }
 
  return counter;
};

Complexity Analysis

Time Complexity

The solution has O(n2) time complexity, since we traverse the whole matrix twice.

Space Complexity

The space complexity is O(n), since we create a hash table keyed by unique rows. In the worst case, its size is n if all rows of the matrix are unique.