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 Difference11563Input ArrayElement Sum1+15+6+3 = 25Digit Sum1+1+5+6+3 = 16Absolute Difference: |25 - 16| = 9
Understanding the Visualization
1
Input Array
Given array [1, 15, 6, 3]
2
Calculate Sums
Element sum = 25, Digit sum = 16
3
Output
Absolute difference = 9
Key Takeaway
🎯 Key Insight: We can calculate both sums in a single pass for optimal efficiency
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