|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# 2352. Equal Row and Column Pairs |
| 4 | +# https://leetcode.com/problems/equal-row-and-column-pairs |
| 5 | +# Medium |
| 6 | + |
| 7 | +=begin |
| 8 | +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. |
| 9 | +
|
| 10 | +A row and column pair is considered equal if they contain the same elements in the same order (i.e., an equal array). |
| 11 | +
|
| 12 | +Example 1: |
| 13 | +Input: grid = [[3,2,1],[1,7,6],[2,7,7]] |
| 14 | +Output: 1 |
| 15 | +Explanation: There is 1 equal row and column pair: |
| 16 | +- (Row 2, Column 1): [2,7,7] |
| 17 | +
|
| 18 | +Example 2: |
| 19 | +Input: grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]] |
| 20 | +Output: 3 |
| 21 | +Explanation: There are 3 equal row and column pairs: |
| 22 | +- (Row 0, Column 0): [3,1,2,2] |
| 23 | +- (Row 2, Column 2): [2,4,2,2] |
| 24 | +- (Row 3, Column 2): [2,4,2,2] |
| 25 | +
|
| 26 | +Constraints: |
| 27 | +n == grid.length == grid[i].length |
| 28 | +1 <= n <= 200 |
| 29 | +1 <= grid[i][j] <= 105 |
| 30 | +=end |
| 31 | + |
| 32 | +# @param {Integer[][]} grid |
| 33 | +# @return {Integer} |
| 34 | +def equal_pairs(grid) |
| 35 | + row_counts = Hash.new(0) |
| 36 | + col_counts = Hash.new(0) |
| 37 | + result = 0 |
| 38 | + grid.each { |el| row_counts[el] += 1 } |
| 39 | + grid.size.times { |i| col_counts[grid.map { |el| el[i - 1] }] += 1 } |
| 40 | + |
| 41 | + row_counts.each do |key, value| |
| 42 | + if !col_counts[key].nil? |
| 43 | + result += value * col_counts[key] |
| 44 | + end |
| 45 | + end |
| 46 | + result |
| 47 | +end |
| 48 | + |
| 49 | +# **************** # |
| 50 | +# TEST # |
| 51 | +# **************** # |
| 52 | + |
| 53 | +require "test/unit" |
| 54 | +class Test_equal_pairs < Test::Unit::TestCase |
| 55 | + def test_ |
| 56 | + assert_equal 1, equal_pairs([[3, 2, 1], [1, 7, 6], [2, 7, 7]]) |
| 57 | + assert_equal 3, equal_pairs([[3, 1, 2, 2], [1, 4, 4, 5], [2, 4, 2, 2], [2, 4, 2, 2]]) |
| 58 | + end |
| 59 | +end |
0 commit comments