Difference Between Element Sum and Digit Sum of an Array

To solve this problem, you can start by computing the element sum and the digit sum separately, then return the absolute difference between these two sums.

The element sum is straightforward: just add up all the numbers in the list.

The digit sum is a bit more complex: you have to break down each number into its individual digits and add those up. This can be achieved by converting each number to a string, then iterating over each character in the string, converting it back to an integer, and adding it to the digit sum.

Here is the Python code that implements this approach:

1
2
3
4
5
class Solution:
    def differenceOfSum(self, nums: List[int]) -> int:
        element_sum = sum(nums)
        digit_sum = sum(int(digit) for num in nums for digit in str(num))
        return abs(element_sum - digit_sum)

In this code, element_sum = sum(nums) calculates the element sum.

digit_sum = sum(int(digit) for num in nums for digit in str(num)) calculates the digit sum. It uses a nested generator expression to iterate over each digit in each number.

Finally, return abs(element_sum - digit_sum) returns the absolute difference between the element sum and the digit sum.

Readable Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
    def differenceOfSum(self, nums: List[int]) -> int:
        # Compute the element sum
        element_sum = 0
        for num in nums:
            element_sum += num

        # Compute the digit sum
        digit_sum = 0
        for num in nums:
            num_as_str = str(num)
            for digit_str in num_as_str:
                digit = int(digit_str)
                digit_sum += digit

        # Compute the absolute difference between the element sum and digit sum
        difference = abs(element_sum - digit_sum)

        return difference