Similar Problems

Similar Problems not available

Equal Row And Column Pairs - Leetcode Solution

Companies:

LeetCode:  Equal Row And Column Pairs Leetcode Solution

Difficulty: Medium

Topics: hash-table matrix array simulation  

Problem Statement:

Given a matrix consisting of integers, check if each row and column contains the same number of pairs of distinct values.

Input:

The input consists of a 2-dimensional matrix of integers.

Output:

Return true if the number of pairs of distinct values in each row and column is the same; otherwise, return false.

Solution:

To solve this problem, we need to iterate through each row and each column of the matrix. For each row and column, we will calculate the number of pairs of distinct values.

We can use a map to keep track of the number of occurrences of each value in the row or column. For each pair of distinct values, we can calculate the number of pairs by multiplying the number of occurrences of each value.

For example, if a row contains the values [1, 2, 3, 2, 1], we can calculate the number of pairs of distinct values as follows:

  • For value 1, there are 2 occurrences.
  • For value 2, there are 2 occurrences.
  • For value 3, there is 1 occurrence.

Therefore, there are (2 * 2) + (2 * 1) = 6 pairs of distinct values.

We can use this approach to calculate the number of pairs of distinct values for each row and column, and then compare the results. If the number of pairs is equal for each row and column, we return true. Otherwise, we return false.

Time Complexity:

The time complexity of this algorithm is O(N^2), where N is the size of the matrix. This is because we need to iterate through each row and each column of the matrix to calculate the number of pairs of distinct values.

Space Complexity:

The space complexity of this algorithm is O(N), where N is the size of the matrix. This is because we need to store the number of occurrences of each value in a map for each row and column. Since there are N rows and N columns, the space complexity is O(N^2).

Code Implementation in Python:

def equal_row_col_pairs(matrix):

n = len(matrix) row_pairs = [0] * n col_pairs = [0] * n

for i in range(n): row_map = {} col_map = {} for j in range(n): # Update row map if matrix[i][j] in row_map: row_map[matrix[i][j]] += 1 else: row_map[matrix[i][j]] = 1

  # Update col map
  if matrix[j][i] in col_map:
    col_map[matrix[j][i]] += 1
  else:
    col_map[matrix[j][i]] = 1

# Calculate row pairs
for val in row_map.values():
  row_pairs[i] += (val * (val - 1)) // 2
  
# Calculate col pairs
for val in col_map.values():
  col_pairs[i] += (val * (val - 1)) // 2
  

Check if row pairs and col pairs are equal

return row_pairs == col_pairs

Test the function

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

print(equal_row_col_pairs(matrix)) # Output: True

Equal Row And Column Pairs Solution Code

1