Skip to content

Commit e9074d2

Browse files
authored
1814. Count Nice Pairs in an Array (#162)
1 parent a8ea93a commit e9074d2

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,7 @@
393393
| 1793 | Maximum Score of a Good Subarray | [Ruby](./algorithms/ruby/1793-maximum-score-of-a-good-subarray.rb) | Hard |
394394
| 1799 | Maximize Score After N Operations | [Ruby](./algorithms/ruby/1799-maximize-score-after-n-operations.rb) | Hard |
395395
| 1802 | Maximum Value at a Given Index in a Bounded Array | [Ruby](./algorithms/ruby/1802-maximum-value-at-a-given-index-in-a-bounded-array.rb) | Medium |
396+
| 1814 | Count Nice Pairs in an Array | [Ruby](./algorithms/ruby/1814-count-nice-pairs-in-an-array.rb) | Medium |
396397
| 1822 | Sign of the Product of an Array | [Ruby](./algorithms/ruby/1822-sign-of-the-product-of-an-array.rb) | Easy |
397398
| 1838 | Frequency of the Most Frequent Element | [Ruby](./algorithms/ruby/1838-frequency-of-the-most-frequent-element.rb) | Medium |
398399
| 1845 | Seat Reservation Manager | [Ruby](./algorithms/ruby/1845-seat-reservation-manager.rb) | Medium |
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# frozen_string_literal: true
2+
3+
# 1814. Count Nice Pairs in an Array
4+
# Medium
5+
# https://leetcode.com/problems/count-nice-pairs-in-an-array
6+
7+
=begin
8+
You are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x. For example, rev(123) = 321, and rev(120) = 21. A pair of indices (i, j) is nice if it satisfies all of the following conditions:
9+
* 0 <= i < j < nums.length
10+
* nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])
11+
Return the number of nice pairs of indices. Since that number can be too large, return it modulo 109 + 7.
12+
13+
Example 1:
14+
Input: nums = [42,11,1,97]
15+
Output: 2
16+
Explanation: The two pairs are:
17+
- (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121.
18+
- (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12.
19+
20+
Example 2:
21+
Input: nums = [13,10,35,24,76]
22+
Output: 4
23+
24+
Constraints:
25+
1 <= nums.length <= 105
26+
0 <= nums[i] <= 109
27+
=end
28+
29+
# @param {Integer[]} nums
30+
# @return {Integer}
31+
def count_nice_pairs(nums)
32+
y = Hash.new { |h, x| h[x] = x - x.to_s.reverse.to_i }
33+
res = 0
34+
c = Hash.new(0)
35+
for x in nums
36+
res += c[y[x]]
37+
c[y[x]] += 1
38+
end
39+
res % 1000000007
40+
end
41+
42+
# **************** #
43+
# TEST #
44+
# **************** #
45+
46+
require "test/unit"
47+
class Test_count_nice_pairs < Test::Unit::TestCase
48+
def test_
49+
assert_equal 2, count_nice_pairs([42, 11, 1, 97])
50+
assert_equal 4, count_nice_pairs([13, 10, 35, 24, 76])
51+
end
52+
end

0 commit comments

Comments
 (0)