Sum of Digit Differences of All Pairs - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [13, 23, 12]
Output: 4
💡 Note: Pair (13,23): digits differ at position 1 (3≠2) → +1. Pair (13,12): digits differ at position 1 (3≠2) → +1. Pair (23,12): digits differ at position 0 (2≠1) and position 1 (3≠2) → +2. Total: 1+1+2=4
Example 2 — All Same Digits
$ Input: nums = [10, 10, 10]
Output: 0
💡 Note: All numbers are identical, so no digit positions differ between any pairs. Total differences = 0
Example 3 — Two Numbers
$ Input: nums = [123, 456]
Output: 3
💡 Note: Only one pair (123,456): all three digit positions differ (1≠4, 2≠5, 3≠6) → +3. Total: 3

Constraints

  • 2 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] < 1010
  • All integers in nums have the same number of digits

Visualization

Tap to expand
Sum of Digit Differences of All Pairs INPUT Array nums: 13 idx 0 23 idx 1 12 idx 2 Digit Positions: 13: digit[0]=1, digit[1]=3 23: digit[0]=2, digit[1]=3 12: digit[0]=1, digit[1]=2 All Pairs: (13,23), (13,12), (23,12) Total: 3 pairs ALGORITHM STEPS 1 Count digits at each pos Track frequency of 0-9 2 For each position Process all n numbers Position 0: digit 1: count=2 (from 13,12) digit 2: count=1 (from 23) 3 Calculate differences Each digit differs from others Formula per position: Pos0: 2*1 = 2 differences Pos1: 1*1 + 1*1 = 2 diffs 4 Sum all positions Total = 2 + 2 = 4 FINAL RESULT Pair-wise verification: (13, 23) pos0: 1!=2 [OK] pos1: 3=3 [--] = 1 (13, 12) pos0: 1=1 [--] pos1: 3!=2 [OK] = 1 (23, 12) pos0: 2!=1 [OK] pos1: 3!=2 [OK] = 2 Total Sum: 1 + 1 + 2 4 Output verified [OK] Key Insight: Instead of comparing all pairs O(n^2), count digit frequencies at each position. For position p: if digit d appears k times, it differs from (n-k) other numbers. Sum contributions: for each digit d at position p, add count[d] * (n - count[d]) / 2. Time: O(n * digits) TutorialsPoint - Sum of Digit Differences of All Pairs | Optimal Solution
Asked in
Google 15 Microsoft 12
8.5K Views
Medium Frequency
~15 min Avg. Time
235 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