LeetCode-in-Java

3153. Sum of Digit Differences of All Pairs

Medium

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:

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:

Solution

public class Solution {
    public long sumDigitDifferences(int[] nums) {
        long result = 0;
        while (nums[0] > 0) {
            int[] counts = new int[10];
            for (int i = 0; i < nums.length; i++) {
                int digit = nums[i] % 10;
                nums[i] = nums[i] / 10;
                result += i - counts[digit];
                counts[digit]++;
            }
        }
        return result;
    }
}