Sum of Digit Differences of All Pairs Problem
Description
LeetCode Problem 3153.
You are given an array nums consisting of positive integers where all integers have the same number of digits.
The digit difference between two integers is the count of different digits that are in the same position in the two integers.
Return the sum of the digit differences between all pairs of integers in nums.
Example 1:
Input: nums = [13,23,12]
Output: 4
Explanation:
We have the following:
- The digit difference between 13 and 23 is 1.
- The digit difference between 13 and 12 is 1.
- The digit difference between 23 and 12 is 2.
So the total sum of digit differences between all pairs of integers is 1 + 1 + 2 = 4.
Example 2:
Input: nums = [10,10,10,10]
Output: 0
Explanation:
All the integers in the array are the same. So the total sum of digit differences between all pairs of integers will be 0.
Constraints:
2 <= nums.length <= 10^51 <= nums[i] < 10^9- All integers in
numshave the same number of digits.
Solution
Approach: Count Digits per Position
All numbers have the same number of digits, so each digit position can be handled on its own. At one position, count how often each digit 0..9 occurs. A digit that occurs v times differs from the other n - v numbers, which gives v * (n - v) ordered pairs. Add this over all digits and positions, then divide by 2 because every pair was counted twice.
Complexity: O(nm) time and O(1) extra space (10 counters), where m is the number of digits.
from collections import Counter
class Solution:
def sumDigitDifferences(self, nums: List[int]) -> int:
n = len(nums)
m = len(str(nums[0]))
ans = 0
for _ in range(m):
cnt = Counter()
for i, x in enumerate(nums):
nums[i], y = divmod(x, 10)
cnt[y] += 1
ans += sum(v * (n - v) for v in cnt.values()) // 2
return ans