LeetCode 2535 - Difference Between Element Sum and Digit Sum of an Array

The problem gives us an array of positive integers called nums. We need to compute two different values from this array. The first value is the element sum, which is simply the sum of every number in the array.

LeetCode Problem 2535

Difficulty: 🟢 Easy
Topics: Array, Math

Solution

Problem Understanding

The problem gives us an array of positive integers called nums. We need to compute two different values from this array.

The first value is the element sum, which is simply the sum of every number in the array. For example, if the array is [1, 15, 6, 3], then the element sum is:

$$1 + 15 + 6 + 3 = 25$$

The second value is the digit sum. Instead of adding the numbers directly, we break every number into its individual digits and add those digits together. Using the same example:

  • 1 contributes 1
  • 15 contributes 1 + 5
  • 6 contributes 6
  • 3 contributes 3

So the digit sum becomes:

$$1 + 1 + 5 + 6 + 3 = 16$$

Finally, we return the absolute difference between these two sums:

$$|25 - 16| = 9$$

The input size is fairly small. The array length can be at most 2000, and each number can be at most 2000. This tells us that even a straightforward implementation will easily run within time limits. There is no need for advanced optimization techniques or complicated data structures.

An important detail is that every number is positive. This guarantees that digit extraction using repeated division and modulo operations behaves cleanly without needing to handle negative signs.

Several edge cases are worth noticing:

  • Arrays containing only single digit numbers. In this situation, the element sum and digit sum are identical, so the answer is 0.
  • Arrays containing numbers like 1000 where zeros appear inside the number. The zeros must still be processed correctly during digit extraction.
  • Arrays with only one element. The algorithm must still correctly compute both sums.
  • Maximum sized inputs. Although the constraints are small, the implementation should still avoid unnecessary overhead.

Approaches

Brute Force Approach

The most direct approach is to compute the element sum and digit sum separately.

First, iterate through the array and compute the sum of all elements. Then, iterate through the array again and extract every digit from every number using repeated modulo and division operations.

For each number:

  • Take num % 10 to get the last digit
  • Add that digit to the digit sum
  • Remove the last digit using num //= 10
  • Repeat until the number becomes 0

This approach is correct because every digit of every number is processed exactly once, and every array element is included exactly once in the element sum.

Although this is called the brute force approach, it is already efficient enough for the given constraints.

Optimal Approach

We can slightly improve the implementation by computing both sums in a single traversal of the array.

Instead of making two separate passes:

  • Add each number directly to the element sum
  • At the same time, extract and accumulate its digits into the digit sum

This avoids an extra pass through the array and keeps the logic compact and efficient.

The key insight is that digit extraction itself is already very cheap because each number contains only a few digits. Since the maximum value is 2000, every number has at most four digits.

Approach Time Complexity Space Complexity Notes
Brute Force O(n × d) O(1) Separate passes for element sum and digit sum
Optimal O(n × d) O(1) Computes both sums in one traversal

Here:

  • n is the number of elements
  • d is the number of digits per element

Since d is at most 4, the runtime is effectively linear.

Algorithm Walkthrough

  1. Initialize two variables, element_sum and digit_sum, both starting at 0.
  2. Traverse through every number in nums.
  3. Add the current number directly to element_sum.
  4. Create a temporary variable equal to the current number. This prevents modifying the original value.
  5. Extract digits one by one using modulo and division:
  • Use temp % 10 to get the last digit.
  • Add that digit to digit_sum.
  • Remove the last digit using integer division: temp //= 10.
  1. Continue the digit extraction loop until the temporary value becomes 0.
  2. After processing all numbers, compute:

$$|element_sum - digit_sum|$$ 8. Return the absolute difference.

Why it works

The algorithm works because every number contributes exactly once to the element sum, and every digit of every number contributes exactly once to the digit sum. The modulo operation retrieves digits from right to left, while integer division removes already processed digits. Since no digits are skipped or duplicated, the computed digit sum is correct. Taking the absolute difference at the end guarantees the required result regardless of which sum is larger.

Python Solution

from typing import List

class Solution:
    def differenceOfSum(self, nums: List[int]) -> int:
        element_sum = 0
        digit_sum = 0

        for num in nums:
            element_sum += num

            temp = num

            while temp > 0:
                digit_sum += temp % 10
                temp //= 10

        return abs(element_sum - digit_sum)

The implementation closely follows the algorithm described earlier.

The variables element_sum and digit_sum store the two required totals. During the loop over nums, each number is immediately added to element_sum.

To compute the digit sum, the code copies the current number into temp. This temporary variable is repeatedly reduced using integer division while extracting the last digit using modulo.

The loop:

while temp > 0:

continues until all digits have been processed. Every extracted digit is added to digit_sum.

Finally, the function returns the absolute difference between the two computed sums.

Go Solution

func differenceOfSum(nums []int) int {
	elementSum := 0
	digitSum := 0

	for _, num := range nums {
		elementSum += num

		temp := num

		for temp > 0 {
			digitSum += temp % 10
			temp /= 10
		}
	}

	diff := elementSum - digitSum

	if diff < 0 {
		return -diff
	}

	return diff
}

The Go implementation mirrors the Python solution very closely.

One small difference is that Go does not provide a built in abs function for integers in the standard library without importing additional packages, so the code manually checks whether the difference is negative.

The problem constraints guarantee that integer overflow is not an issue because the maximum possible sums are very small relative to Go's integer range.

An empty slice does not need special handling because the constraints guarantee at least one element.

Worked Examples

Example 1

Input:

nums = [1, 15, 6, 3]

Step by Step Trace

Current Number Element Sum Digits Processed Digit Sum
1 1 1 1
15 16 1, 5 7
6 22 6 13
3 25 3 16

Final calculation:

$$|25 - 16| = 9$$

Output:

9

Example 2

Input:

nums = [1, 2, 3, 4]

Step by Step Trace

Current Number Element Sum Digits Processed Digit Sum
1 1 1 1
2 3 2 3
3 6 3 6
4 10 4 10

Final calculation:

$$|10 - 10| = 0$$

Output:

0

Complexity Analysis

Measure Complexity Explanation
Time O(n × d) Each number and each digit is processed once
Space O(1) Only a few variables are used

The runtime depends on both the number of elements and the number of digits per element. Since each integer is at most 2000, every number has at most four digits, making the digit processing effectively constant time. Therefore, the overall runtime behaves like linear time relative to the array size.

The algorithm uses constant extra memory because it stores only a few integer variables regardless of input size.

Test Cases

from typing import List

class Solution:
    def differenceOfSum(self, nums: List[int]) -> int:
        element_sum = 0
        digit_sum = 0

        for num in nums:
            element_sum += num

            temp = num

            while temp > 0:
                digit_sum += temp % 10
                temp //= 10

        return abs(element_sum - digit_sum)

solution = Solution()

assert solution.differenceOfSum([1, 15, 6, 3]) == 9  # provided example
assert solution.differenceOfSum([1, 2, 3, 4]) == 0  # all single digit numbers
assert solution.differenceOfSum([10]) == 9  # single number with zero digit
assert solution.differenceOfSum([999]) == 972  # large digit contribution difference
assert solution.differenceOfSum([1000, 2000]) == 2997  # numbers containing many zeros
assert solution.differenceOfSum([5]) == 0  # single single-digit number
assert solution.differenceOfSum([11, 22, 33]) == 54  # repeated multi-digit numbers
assert solution.differenceOfSum([2000] * 2000) == 3992000  # stress test near limits
Test Why
[1, 15, 6, 3] Verifies the provided example
[1, 2, 3, 4] Confirms zero difference for single digit values
[10] Tests handling of internal zero digits
[999] Tests large difference from digit decomposition
[1000, 2000] Ensures zeros are processed correctly
[5] Smallest meaningful single element case
[11, 22, 33] Tests repeated multi digit processing
[2000] * 2000 Stress test near maximum constraints

Edge Cases

One important edge case occurs when every number is already a single digit. In that situation, the digit sum and element sum are identical because each number contributes exactly one digit equal to itself. A careless implementation might overcomplicate the logic, but this solution naturally handles it because digit extraction simply returns the original number.

Another important case involves numbers containing zeros, such as 1000. Some buggy implementations accidentally skip zeros or terminate digit extraction incorrectly. This implementation avoids that issue because the modulo operation correctly extracts 0 digits, and the division loop continues until the entire number has been processed.

A third edge case is the smallest possible array size, where the array contains only one element. Algorithms that incorrectly assume multiple iterations or rely on pairwise processing can fail here. This implementation works correctly because each number is processed independently.

Finally, the maximum constraint case tests whether the implementation remains efficient under heavy input. Even with 2000 numbers, each containing up to four digits, the algorithm performs only a small constant amount of work per element, so it remains easily within acceptable runtime limits.