Count Nice Pairs in an Array - Problem
You are given an array nums consisting of non-negative integers. Your task is to find all "nice pairs" of indices in the array.
First, let's define what rev(x) means: it's the reverse of a non-negative integer x. For example:
rev(123) = 321rev(120) = 21(leading zeros are dropped)rev(5) = 5
A pair of indices (i, j) is considered "nice" if it satisfies these conditions:
0 โค i < j < nums.length(valid indices with i before j)nums[i] + rev(nums[j]) = nums[j] + rev(nums[i])(the magic condition!)
Goal: Return the total number of nice pairs. Since this number can be very large, return it modulo 109 + 7.
The key insight is that the condition can be rearranged as: nums[i] - rev(nums[i]) = nums[j] - rev(nums[j])
Input & Output
example_1.py โ Basic Example
$
Input:
nums = [42, 11, 1, 97]
โบ
Output:
2
๐ก Note:
The 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.py โ All Same Differences
$
Input:
nums = [13, 10, 35, 24, 76]
โบ
Output:
4
๐ก Note:
All numbers have the same difference value: 13-31=-18, 10-01=9, 35-53=-18, 24-42=-18, 76-67=9. We have 3 numbers with diff=-18 giving C(3,2)=3 pairs, and 2 numbers with diff=9 giving C(2,2)=1 pair. Total: 4 pairs.
example_3.py โ Edge Case
$
Input:
nums = [1, 2, 3]
โบ
Output:
0
๐ก Note:
No nice pairs exist. Differences are: 1-1=0, 2-2=0, 3-3=0. Wait, all have difference 0, so we have C(3,2)=3 pairs! Actually the answer should be 3, not 0.
Visualization
Tap to expand
Understanding the Visualization
1
Original Condition
nums[i] + rev(nums[j]) = nums[j] + rev(nums[i]) seems complex to check directly
2
Mathematical Rearrangement
Subtract rev(nums[j]) and nums[i] from both sides to get: rev(nums[i]) - nums[i] = rev(nums[j]) - nums[j]
3
Simplified Form
Or equivalently: nums[i] - rev(nums[i]) = nums[j] - rev(nums[j]). Now we just need to group by this difference!
4
Count Combinations
For each group of k numbers with same difference, there are k*(k-1)/2 pairs
Key Takeaway
๐ฏ Key Insight: By transforming the complex pair condition into a simple grouping problem, we reduce the time complexity from O(nยฒ) to O(n) while making the solution more elegant and intuitive!
Time & Space Complexity
Time Complexity
O(n)
Single pass through the array, with O(log nums[i]) time to reverse each number
โ Linear Growth
Space Complexity
O(n)
Hash map can store up to n different difference values in worst case
โก Linearithmic Space
Constraints
- 1 โค nums.length โค 105
- 0 โค nums[i] โค 109
- Return the result modulo 109 + 7
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code