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

You are given a positive integer array nums.

The element sum is the sum of all the elements in nums.

The digit sum is the sum of all the digits (not necessarily distinct) that appear in nums.

Return the absolute difference between the element sum and digit sum of nums.

Note: The absolute difference between two integers x and y is defined as |x - y|.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,15,6,3]
Output: 9
💡 Note: Element sum: 1 + 15 + 6 + 3 = 25. Digit sum: 1 + 1 + 5 + 6 + 3 = 16. Absolute difference: |25 - 16| = 9.
Example 2 — Single Digits
$ Input: nums = [1,2,3,4]
Output: 0
💡 Note: Element sum: 1 + 2 + 3 + 4 = 10. Digit sum: 1 + 2 + 3 + 4 = 10. Absolute difference: |10 - 10| = 0.
Example 3 — Large Numbers
$ Input: nums = [99,88]
Output: 153
💡 Note: Element sum: 99 + 88 = 187. Digit sum: 9 + 9 + 8 + 8 = 34. Absolute difference: |187 - 34| = 153.

Constraints

  • 1 ≤ nums.length ≤ 2000
  • 1 ≤ nums[i] ≤ 2000

Visualization

Tap to expand
Element Sum vs Digit Sum INPUT nums = [1, 15, 6, 3] 1 idx 0 15 idx 1 6 idx 2 3 idx 3 Element Sum: 1 + 15 + 6 + 3 = 25 Digits in Array: 1 1 5 6 3 Digit Sum: 1 + 1 + 5 + 6 + 3 = 16 ALGORITHM STEPS 1 Initialize Sums elementSum = 0 digitSum = 0 2 Loop Each Number For each num in array: Add num to elementSum 3 Extract Digits While num > 0: digit = num % 10 num = num / 10 Add digit to digitSum 4 Calculate Difference Return |elementSum - digitSum| |25 - 16| = 9 Iteration: num=15 15%10=5, 15/10=1, 1%10=1 FINAL RESULT Element Sum 25 minus Digit Sum 16 = OUTPUT 9 OK - |25 - 16| = 9 Key Insight: The element sum is always greater than or equal to the digit sum. This is because multi-digit numbers contribute their full value to element sum but only individual digits (which sum to less) to the digit sum. For example: 15 contributes 15 to element sum, but only 1+5=6 to digit sum. TutorialsPoint - Difference Between Element Sum and Digit Sum of an Array | Single-Pass Approach
Asked in
Amazon 15 Google 12
34.2K Views
Medium Frequency
~8 min Avg. Time
856 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