Count Nice Pairs in an Array - Problem

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:

  • 0 <= i < j < nums.length
  • nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])

Return the number of nice pairs of indices. Since that number can be too large, return it modulo 10⁹ + 7.

Input & Output

Example 1 — Basic Case
$ Input: nums = [42,11,1,97]
Output: 2
💡 Note: The two nice pairs are (0,3) and (1,2). For (0,3): 42 + rev(97) = 42 + 79 = 121, and 97 + rev(42) = 97 + 24 = 121. For (1,2): 11 + rev(1) = 11 + 1 = 12, and 1 + rev(11) = 1 + 11 = 12.
Example 2 — Single Nice Pair
$ Input: nums = [13,10,35,24,76]
Output: 4
💡 Note: Multiple pairs satisfy the nice condition when nums[i] - rev(nums[i]) equals nums[j] - rev(nums[j]).
Example 3 — No Nice Pairs
$ Input: nums = [123,456]
Output: 1
💡 Note: 123 + rev(456) = 123 + 654 = 777, and 456 + rev(123) = 456 + 321 = 777. Since both sums are equal, this forms 1 nice pair. Using the difference approach: 123-321=-198, 456-654=-198, so they have the same difference and form 1 nice pair.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Count Nice Pairs in an Array INPUT nums array: 42 i=0 11 i=1 1 i=2 97 i=3 rev() function: rev(42) = 24 rev(11) = 11 rev(1) = 1 rev(97) = 79 Nice Pair Condition: nums[i] + rev(nums[j]) == nums[j] + rev(nums[i]) where 0 <= i < j < n ALGORITHM STEPS 1 Transform Equation nums[i] - rev(nums[i]) == nums[j] - rev(nums[j]) 2 Compute diff values diff[i] = nums[i] - rev(nums[i]) 42 - 24 = 18 11 - 11 = 0 1 - 1 = 0 97 - 79 = 18 diff = [18,0,0,18] 3 Use HashMap Count freq of each diff 18 --> 2 0 --> 2 (key: count) 4 Count Pairs For each new element, add existing count FINAL RESULT Nice Pairs Found: Pair 1: (i=1, j=2) diff[1] = 0 diff[2] = 0 [OK] Pair 2: (i=0, j=3) diff[0] = 18 diff[3] = 18 [OK] Pairs with same diff: diff=0: 1 pair (1,2) diff=18: 1 pair (0,3) OUTPUT 2 Total nice pairs: 2 Key Insight: Rearrange nums[i] + rev(nums[j]) == nums[j] + rev(nums[i]) to get: nums[i] - rev(nums[i]) == nums[j] - rev(nums[j]) This means we just need to count pairs with the same "diff" value using a HashMap. O(n) time! TutorialsPoint - Count Nice Pairs in an Array | Hash Approach
Asked in
Facebook 25 Google 18
24.3K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen