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: 0
💡 Note: 123 + rev(456) = 123 + 654 = 777, but 456 + rev(123) = 456 + 321 = 777. Actually this is a nice pair! The difference approach: 123-321=-198, 456-654=-198, so they have same difference and form 1 nice pair.

Constraints

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

Visualization

Tap to expand
Count Nice Pairs: Transform and GroupInput: [42, 11, 1, 97]421119742-24=1811-11=01-1=097-79=18Group: diff = 0Group: diff = 18C(2,2) = 1 pairC(2,2) = 1 pairTotal: 2 nice pairsPairs: (0,3) and (1,2)
Understanding the Visualization
1
Input Array
[42, 11, 1, 97] - find nice pairs
2
Transform
Calculate num - reverse(num) for each element
3
Count Pairs
Elements with same difference form nice pairs
Key Takeaway
🎯 Key Insight: Transform the equation to find elements with the same difference value
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