Problem Description
Given an array of non-negative integers, a pair of indices (i, j) is defined as nice if 0 <= i < j and the following equation holds: nums[i] + rev(nums[j]) == nums[j] + rev(nums[i]), where rev(x) represents the reverse of the integer x. The task is to count the total number of nice pairs in the array and return the count modulo 10^9 + 7.
Key Insights
- The core observation is that the condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])).
- This allows grouping numbers by the computed difference d = x - rev(x).
- For each group, if there are count elements, they can form count*(count-1)/2 nice pairs.
- A hash map can be used for efficient counting and grouping.
Space and Time Complexity
Time Complexity: O(n) where n is the number of elements in the array, since we iterate over the array once. Space Complexity: O(n) in the worst-case scenario, for the hash map storing counts for each unique computed difference.
Solution
We compute a transformed value for each number as d = number - rev(number). The condition for a pair to be nice translates into both elements having the same d value. We use a hash map (or dictionary) to maintain the frequency of each d value. For each number in the array, we update the frequency and count the nice pairs formed with elements already seen having the same d value. The answer is obtained by summing these pair counts and then taking modulo 10^9 + 7.