Skip to content

Commit 15429c3

Browse files
committed
2352. Equal Row and Column Pairs
1 parent 3de8501 commit 15429c3

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,7 @@
190190
| 2316 | Count Unreachable Pairs of Nodes in an Undirected Graph | [Ruby](./algorithms/ruby/2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph.rb) | Medium |
191191
| 2336 | Smallest Number in Infinite Set | [Ruby](./algorithms/ruby/2336-smallest-number-in-infinite-set.rb) | Medium |
192192
| 2348 | Number of Zero-Filled Subarrays | [Ruby](./algorithms/ruby/2348-number-of-zero-filled-subarrays.rb) | Medium |
193+
| 2352 | Equal Row and Column Pairs | [Ruby](./algorithms/ruby/2352-equal-row-and-column-pairs.rb) | Medium |
193194
| 2360 | Longest Cycle in a Graph | [Ruby](./algorithms/ruby/2360-longest-cycle-in-a-graph.rb) | Hard |
194195
| 2390 | Removing Stars From a String | [Ruby](./algorithms/ruby/2390-removing-stars-from-a-string.rb) | Medium |
195196
| 2405 | Count Days Spent Together | [Ruby](./algorithms/ruby/2405-optimal-partition-of-string.rb) | Medium |
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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

Comments
 (0)