Difference Between Element Sum and Digit Sum of an Array - Problem

You're given a positive integer array nums, and your task is to calculate two different types of sums and find their absolute difference.

Element Sum: Simply add up all the numbers in the array as they are.
Digit Sum: Break down each number into its individual digits, then add up all these digits.

For example, if you have the array [123, 45]:
• Element sum = 123 + 45 = 168
• Digit sum = (1+2+3) + (4+5) = 6 + 9 = 15
• Absolute difference = |168 - 15| = 153

Return the absolute difference between these two sums. The absolute difference ensures we always get a positive result, regardless of which sum is larger.

Input & Output

example_1.py — Basic Case
$ Input: [1,15,6,3]
Output: 9
💡 Note: Element sum = 1+15+6+3 = 25, Digit sum = 1+(1+5)+6+3 = 16, Difference = |25-16| = 9
example_2.py — Larger Numbers
$ Input: [1,2,3,4]
Output: 0
💡 Note: Element sum = 1+2+3+4 = 10, Digit sum = 1+2+3+4 = 10, Difference = |10-10| = 0
example_3.py — Multi-digit Numbers
$ Input: [123,456]
Output: 564
💡 Note: Element sum = 123+456 = 579, Digit sum = (1+2+3)+(4+5+6) = 21, Difference = |579-21| = 558

Constraints

  • 1 ≤ nums.length ≤ 2000
  • 1 ≤ nums[i] ≤ 2000
  • All numbers are positive integers

Visualization

Tap to expand
Dual Counter SystemElement Sum Counter168123 + 45Digit Sum Counter15(1+2+3) + (4+5)Input:123Add whole numberExtract & add digitsFinal Result|168 - 15| = 153
Understanding the Visualization
1
Setup Two Counters
Initialize element_sum and digit_sum to 0
2
Process Each Item
For each number, add it to element_sum
3
Extract Digits
Use num % 10 to get last digit, num / 10 to remove it
4
Add to Digit Sum
Add each extracted digit to digit_sum
5
Calculate Difference
Return |element_sum - digit_sum|
Key Takeaway
🎯 Key Insight: We can efficiently solve this in one pass by maintaining two running totals - one for the numbers themselves, another for their individual digits extracted using modulo arithmetic.
Asked in
Google 12 Amazon 8 Microsoft 6 Meta 4
23.4K Views
Medium Frequency
~8 min Avg. Time
845 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