# Difference Between Element Sum and Digit Sum of an Array
**Difficulty:** EASY
[External](https://leetcode.com/problems/difference-between-element-sum-and-digit-sum-of-an-array)
Canonical: https://scaleengineer.com/dsa/problems/difference-between-element-sum-and-digit-sum-of-an-array
**Patterns:** [Math](https://scaleengineer.com/dsa/patterns/math)
**Data structures:** 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** that the absolute difference between two integers `x` and `y` is defined as `|x - y|`.

**Example 1:**

**Input:** nums = [1,15,6,3]
**Output:** 9
**Explanation:** 
The element sum of nums is 1 + 15 + 6 + 3 = 25.
The digit sum of nums is 1 + 1 + 5 + 6 + 3 = 16.
The absolute difference between the element sum and digit sum is |25 - 16| = 9.

**Example 2:**

**Input:** nums = [1,2,3,4]
**Output:** 0
**Explanation:**
The element sum of nums is 1 + 2 + 3 + 4 = 10.
The digit sum of nums is 1 + 2 + 3 + 4 = 10.
The absolute difference between the element sum and digit sum is |10 - 10| = 0.

**Constraints:**

* `1 <= nums.length <= 2000`
* `1 <= nums[i] <= 2000`

# Approaches
## String Conversion Method
This is a straightforward but least efficient approach. It calculates the element sum by iterating through the array. For the digit sum, it converts each number to a string and then iterates through the characters of the string, summing up their numeric values. This method is generally slower due to the overhead associated with string manipulation.
**Time:** O(N * D), where N is the length of the array and D is the maximum number of digits in a number. While asymptotically similar to other approaches, the constant factors are higher due to string operations, making it slower in practice. · **Space:** O(D), for storing the string representation of a number. Since D, the maximum number of digits, is small and constant (max 4 for numbers up to 2000), this is effectively O(1) space.
**Pros:** The logic for extracting digits might be intuitive for those familiar with string manipulation.
**Cons:** Significantly less performant than arithmetic-based approaches due to the overhead of string creation and character parsing.
### Explanation
This approach calculates the digit sum by first converting each number into its string representation. Then, it iterates through the characters of the string, converts each character back to a digit, and adds it to the digit sum. The element sum can be calculated in the same loop or a separate one. While intuitive, this method is generally slower due to the overhead associated with string manipulation.

Here is an implementation combining both calculations in a single loop:
```java
class Solution {
    public int differenceOfSum(int[] nums) {
        int elementSum = 0;
        int digitSum = 0;

        for (int num : nums) {
            elementSum += num;
            
            String s = String.valueOf(num);
            for (char c : s.toCharArray()) {
                digitSum += c - '0';
            }
        }

        return Math.abs(elementSum - digitSum);
    }
}
```
### Algorithm
*   Initialize `elementSum` and `digitSum` to 0.
*   Iterate through each number `num` in the input array `nums`.
*   Add the `num` to `elementSum`.
*   Convert `num` to its string representation.
*   Iterate through each character of the string.
*   Convert the character back to an integer (e.g., `c - '0'`) and add it to `digitSum`.
*   After the loop, return the absolute difference between `elementSum` and `digitSum`.

## Two-Pass Arithmetic Iteration
This approach uses two separate loops over the input array. The first loop computes the `elementSum` by summing up all the numbers. The second loop computes the `digitSum` by iterating through the numbers again and, for each number, using arithmetic operations (modulo and division) to extract and sum its digits.
**Time:** O(N * D). The algorithm makes two passes over the array of size N. The second pass involves a loop for digits (D). The total time is `O(N) + O(N*D)`, which simplifies to `O(N*D)`. Since D is a small constant, this is effectively O(N). · **Space:** O(1). Only a few variables are used, requiring constant extra space.
**Pros:** Clear separation of concerns, making the code easy to understand and debug.; More efficient than string-based methods.
**Cons:** Requires two passes over the data, which is less efficient than a single-pass solution.
### Explanation
This method separates the two summation concerns into two distinct passes. The first pass calculates the sum of all elements. The second pass calculates the sum of all digits using efficient arithmetic operations. This separation can make the code easy to read but is slightly less optimal than a single pass.

Here is the Java implementation:
```java
class Solution {
    public int differenceOfSum(int[] nums) {
        int elementSum = 0;
        // First pass: calculate element sum
        for (int num : nums) {
            elementSum += num;
        }

        int digitSum = 0;
        // Second pass: calculate digit sum
        for (int num : nums) {
            int currentNum = num;
            while (currentNum > 0) {
                digitSum += currentNum % 10;
                currentNum /= 10;
            }
        }

        return Math.abs(elementSum - digitSum);
    }
}
```
### Algorithm
*   Initialize `elementSum` to 0.
*   **First Pass:** Iterate through `nums` and add each element to `elementSum`.
*   Initialize `digitSum` to 0.
*   **Second Pass:** Iterate through `nums` again. For each number:
    *   Use a `while` loop that continues as long as the number is positive.
    *   In the loop, get the last digit using the modulo operator (`num % 10`) and add it to `digitSum`.
    *   Remove the last digit by performing integer division (`num / 10`).
*   Finally, return `Math.abs(elementSum - digitSum)`.

## Single-Pass Arithmetic Iteration
This is the most efficient approach. It calculates both the element sum and the digit sum within a single loop over the array. By processing each number completely in one go, it minimizes redundant iterations and offers the best performance.
**Time:** O(N * D), where N is the array length and D is the max number of digits. This is linear O(N) because D is a small constant. This approach is the fastest in practice as it minimizes loop overhead. · **Space:** O(1). It uses a constant amount of extra space.
**Pros:** Most efficient solution as it traverses the array only once.; Minimal memory usage.
**Cons:** The logic inside the loop is slightly more combined compared to the two-pass approach, which might be perceived as marginally less readable by some.
### Explanation
In a single iteration over the array, we can perform both required calculations. For each number, we add it to the `elementSum` and then use a nested loop to extract its digits and add them to the `digitSum`.

Here is the optimized Java code:
```java
class Solution {
    public int differenceOfSum(int[] nums) {
        int elementSum = 0;
        int digitSum = 0;

        for (int num : nums) {
            elementSum += num;
            
            int currentNum = num;
            while (currentNum > 0) {
                digitSum += currentNum % 10;
                currentNum /= 10;
            }
        }

        // For positive integers, elementSum is always >= digitSum.
        // So, Math.abs() is not strictly necessary but ensures correctness.
        return elementSum - digitSum;
    }
}
```
### Algorithm
*   Initialize `elementSum` and `digitSum` to 0.
*   Start a single loop to iterate through each `num` in the `nums` array.
*   Inside the loop, add `num` to `elementSum`.
*   Also inside the loop, use a nested `while` loop to process the digits of the current `num`:
    *   Extract the last digit using `num % 10` and add it to `digitSum`.
    *   Remove the last digit using `num / 10`.
*   After the main loop completes, both sums are ready.
*   Return the difference `elementSum - digitSum`.

# Solutions
### Java

```java
class Solution {
public
  int differenceOfSum(int[] nums) {
    int a = 0, b = 0;
    for (int x : nums) {
      a += x;
      for (; x > 0; x /= 10) {
        b += x % 10;
      }
    }
    return Math.abs(a - b);
  }
}

```

### CPP

```cpp
class Solution {
public:
  int differenceOfSum(vector<int> &nums) {
    int a = 0, b = 0;
    for (int x : nums) {
      a += x;
      for (; x; x /= 10) {
        b += x % 10;
      }
    }
    return abs(a - b);
  }
};

```

### Python

```python
class Solution:
    def differenceOfSum(self, nums: List[int]) -> int: a, b = sum(nums), 0 for x in nums: while x: b += x % 10 x //= 10 return abs(a - b)

```
