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: [13, 23, 12]13231213 vs 23: 1 diff13 vs 12: 1 diff23 vs 12: 2 diffAll Pair Comparisons:1 + 1 + 2 = 4Result: 4
Understanding the Visualization
1
Input
Array of numbers with same digit count: [13, 23, 12]
2
Process
Compare digits at same positions for all pairs
3
Output
Sum of all digit differences: 4
Key Takeaway
🎯 Key Insight: Instead of comparing every pair directly, count digit frequencies at each position and use math to calculate total differences efficiently
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