Talentd
FleetCode
Make and follow sheets.Sign in

Difference Between Element Sum and Digit Sum of an Array solution and explanation

EasyArrayMath5 min read85.3% acceptanceUpdated 9 Apr 2026
2535. Difference Between Element Sum and Digit Sum of an Array | Weekly Contest 328 | LeetCode 2535Bro Coders · 3:22 · 1K viewsWatch on YouTube
9 more videos on this problem
  1. 2535. Difference Between Element Sum and Digit Sum of an Array | Weekly Contest 328 | LeetCode 2535Bro Coders · 3:22 · 1K views
  2. 2535. Difference Between Element Sum and Digit Sum of an Array | Weekly Contest 328 | in HindiZigZagCode · 6:11 · 609 views
  3. Leetcode 2535 || Difference Between Element Sum and Digit Sum of an Array|| Leetcode Contest EasyCoding Techniques with Komal | Newton School · 5:42 · 595 views
  4. Leetcode 2535: Difference Between Element Sum and Digit Sum of an ArrayAlgorithms Casts · 4:01 · 505 views
  5. Difference Between Element Sum and Digit Sum of an Array | LeetCode 2535 | CppCodeClips with Abhishek Ranjan · 4:02 · 434 views
  6. 2535. Difference Between Element Sum and Digit Sum of an Array (Leetcode Easy)Programming Live with Larry · 1:55 · 406 views
  7. Difference Between Element Sum and Digit Sum of an Array | Leetcode 2535 | Leetcode Contest 328Tech Courses · 3:06 · 249 views
  8. 2535. Difference Between Element Sum and Digit Sum of an Array||Java SolutionTech Demand · 5:59 · 197 views
  9. 2535. Difference Between Element Sum and Digit Sum of an Array|Java|Leetcode|Math Based|FundamentalsCoding with Tamilarasan · 6:17 · 174 views
  10. LeetCode 2535 : Difference Between Element Sum and Digit Sum of Array || EASY || JAVA || SolutionCodeGPT · 10:08 · 154 views

The 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

Approach overview

Problem Overview: You are given an integer array nums. Compute two values: the sum of all elements in the array and the sum of every digit from those elements. The task is to return the absolute difference between these two sums.

Approach 1: Iterative Digit Extraction to Compute Sums (Time: O(n * d), Space: O(1))

This approach processes each number in the array and extracts its digits one by one. First, iterate through the array and accumulate the element sum. Then for each number, repeatedly apply num % 10 to get the last digit and add it to the digit sum, followed by num /= 10 to remove the digit. This continues until the number becomes zero. The key idea is that digit extraction can be done using simple arithmetic operations without converting numbers to strings. If the array has n elements and each number contains up to d digits, the time complexity becomes O(n * d). Space complexity remains O(1) since only running totals are stored. This is the most straightforward implementation and works well in any language.

Approach 2: Mathematical Handling by Modulo (Time: O(n * d), Space: O(1))

This version focuses on computing the difference directly using arithmetic properties instead of maintaining two separate totals. For each element, add the full number to the element sum while simultaneously subtracting its digits from a running difference using modulo operations. Each iteration extracts digits with % 10 and reduces the number using integer division by 10. The insight is that the difference between element sum and digit sum can be accumulated incrementally rather than calculated at the end. This keeps the logic tight and avoids maintaining multiple aggregates. Complexity remains O(n * d) because every digit of every number must still be processed, while space usage stays O(1). The algorithm relies purely on arithmetic operations commonly used in math problems.

Both approaches rely on simple iteration over the input array, a common pattern in array problems. Digit extraction using modulo is also a fundamental technique in many math and number manipulation questions.

Recommended for interviews: Interviewers typically expect the iterative digit extraction approach. It clearly demonstrates that you understand how to manipulate numbers using modulo and division. The mathematical accumulation variant is slightly cleaner but conceptually the same. Showing the basic digit extraction first proves your understanding, while writing it in a compact form shows implementation maturity.

Approach 1: Iterative Digit Extraction to Compute Sums

This approach uses iteration to extract each digit for calculating the digit sum. The element sum is simply the sum of all numbers. For the digit sum, convert each number to its constituent digits by using modulo and integer division.

def difference_element_digit_sum(nums):
    element_sum = sum(nums)
    digit_sum = sum(int(digit) for num in nums for digit in str(num))
    return abs(element_sum - digit_sum)

nums = [1, 15, 6, 3]
print(difference_element_digit_sum(nums))
public class Solution {
    public static int differenceElementDigitSum(int[] nums) {
        int elementSum = 0, digitSum = 0;
        for (int num : nums) {
            elementSum += num;
            int temp = num;
            while (temp > 0) {
                digitSum += temp % 10;
                temp /= 10;
            }
        }
        return Math.abs(elementSum - digitSum);
    }
    public static void main(String[] args) {
        int[] nums = {1, 15, 6, 3};
        System.out.println(differenceElementDigitSum(nums));
    }
}
#include <iostream>
#include <vector>
#include <cmath>

int differenceElementDigitSum(std::vector<int>& nums) {
    int elementSum = 0, digitSum = 0;
    for (int num : nums) {
        elementSum += num;
        int temp = num;
        while (temp > 0) {
            digitSum += temp % 10;
            temp /= 10;
        }
    }
    return std::abs(elementSum - digitSum);
}

int main() {
    std::vector<int> nums = {1, 15, 6, 3};
    std::cout << differenceElementDigitSum(nums) << std::endl;
    return 0;
}
function differenceElementDigitSum(nums) {
    const elementSum = nums.reduce((acc, num) => acc + num, 0);
    const digitSum = nums.reduce((acc, num) => acc + Array.from(String(num), Number).reduce((a, b) => a + b, 0), 0);
    return Math.abs(elementSum - digitSum);
}

console.log(differenceElementDigitSum([1, 15, 6, 3]));
#include <stdio.h>
#include <stdlib.h>

int differenceElementDigitSum(int* nums, int numsSize) {
    int elementSum = 0, digitSum = 0;
    for (int i = 0; i < numsSize; i++) {
        elementSum += nums[i];
        int num = nums[i];
        while (num > 0) {
            digitSum += num % 10;
            num /= 10;
        }
    }
    return abs(elementSum - digitSum);
}

int main() {
    int nums[] = {1, 15, 6, 3};
    int result = differenceElementDigitSum(nums, 4);
    printf("%d\n", result);
    return 0;
}
using System;
using System.Linq;

class Solution {
    static int DifferenceElementDigitSum(int[] nums) {
        int elementSum = nums.Sum();
        int digitSum = nums.SelectMany(num => num.ToString().Select(d => d - '0')).Sum();
        return Math.Abs(elementSum - digitSum);
    }

    static void Main() {
        int[] nums = {1, 15, 6, 3};
        Console.WriteLine(DifferenceElementDigitSum(nums));
    }
}

This Python solution utilizes list comprehensions to succinctly compute the digit sum by converting each integer to a string and summing the digits.

Complexity

Time Complexity: O(n * log(max(nums[i]))), where n is the number of elements and max(nums[i]) is the maximum number in nums. Space Complexity: O(1).

Try this approach in the editor

Approach 2: Mathematical Handling by Modulo

This approach is the same iterative technique but focuses on optimizing the handling by utilizing mathematical operations directly to extract each digit, avoiding string conversions.

def difference_element_digit_sum(nums):
    element_sum = sum(nums)
    digit_sum = 0
    for num in nums:
        while num > 0:
            digit_sum += num % 10
            num //= 10
    return abs(element_sum - digit_sum)

nums = [1, 2, 3, 4]
print(difference_element_digit_sum(nums))
public class Solution {
    public static int differenceElementDigitSum(int[] nums) {
        int elementSum = 0, digitSum = 0;
        for (int num : nums) {
            elementSum += num;
            int temp = num;
            while (temp > 0) {
                digitSum += temp % 10;
                temp /= 10;
            }
        }
        return Math.abs(elementSum - digitSum);
    }
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4};
        System.out.println(differenceElementDigitSum(nums));
    }
}
#include <iostream>
#include <vector>
#include <cmath>

int differenceElementDigitSum(std::vector<int>& nums) {
    int elementSum = 0, digitSum = 0;
    for (int num : nums) {
        elementSum += num;
        int temp = num;
        while (temp > 0) {
            digitSum += temp % 10;
            temp /= 10;
        }
    }
    return std::abs(elementSum - digitSum);
}

int main() {
    std::vector<int> nums = {1, 2, 3, 4};
    std::cout << differenceElementDigitSum(nums) << std::endl;
    return 0;
}
function differenceElementDigitSum(nums) {
    let elementSum = nums.reduce((acc, num) => acc + num, 0);
    let digitSum = 0;
    nums.forEach(num => {
        while (num > 0) {
            digitSum += num % 10;
            num = Math.floor(num / 10);
        }
    });
    return Math.abs(elementSum - digitSum);
}

console.log(differenceElementDigitSum([1, 2, 3, 4]));
#include <stdio.h>
#include <stdlib.h>

int differenceElementDigitSum(int* nums, int numsSize) {
    int elementSum = 0, digitSum = 0;
    for (int i = 0; i < numsSize; i++) {
        elementSum += nums[i];
        int num = nums[i];
        while (num > 0) {
            digitSum += num % 10;
            num /= 10;
        }
    }
    return abs(elementSum - digitSum);
}

int main() {
    int nums[] = {1, 2, 3, 4};
    int result = differenceElementDigitSum(nums, 4);
    printf("%d\n", result);
    return 0;
}
using System;
using System.Linq;

class Solution {
    static int DifferenceElementDigitSum(int[] nums) {
        int elementSum = nums.Sum();
        int digitSum = 0;
        foreach (int num in nums) {
            int temp = num;
            while (temp > 0) {
                digitSum += temp % 10;
                temp /= 10;
            }
        }
        return Math.Abs(elementSum - digitSum);
    }

    static void Main() {
        int[] nums = {1, 2, 3, 4};
        Console.WriteLine(DifferenceElementDigitSum(nums));
    }
}

This Python solution iterates through each element, continuously dividing by 10 and using modulus to extract digits, avoiding string operations entirely.

Complexity

Time Complexity: O(n * log(max(nums[i]))), where n is the number of elements and max(nums[i]) is the maximum number in nums. Space Complexity: O(1).

Try this approach in the editor

Approach 3: Simulation

We traverse the array nums, calculate the sum of the elements x and the sum of the digits y, and finally return |x - y|. Since x is always greater than or equal to y, we can directly return x - y.

The time complexity is O(n times log_{10} M), where n and M are the length of the array nums and the maximum value of the elements in the array, respectively. The space complexity is O(1).

function differenceOfSum(nums: number[]): number {
    let [x, y] = [0, 0];
    for (let v of nums) {
        x += v;
        for (; v; v = Math.floor(v / 10)) {
            y += v % 10;
        }
    }
    return x - y;
}
func differenceOfSum(nums []int) int {
	var x, y int
	for _, v := range nums {
		x += v
		for ; v > 0; v /= 10 {
			y += v % 10
		}
	}
	return x - y
}
impl Solution {
    pub fn difference_of_sum(nums: Vec<i32>) -> i32 {
        let mut x = 0;
        let mut y = 0;

        for &v in &nums {
            x += v;
            let mut num = v;
            while num > 0 {
                y += num % 10;
                num /= 10;
            }
        }

        x - y
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Iterative Digit Extraction to Compute Sums

Time Complexity: O(n * log(max(nums[i]))), where n is the number of elements and max(nums[i]) is the maximum number in nums. Space Complexity: O(1).

Mathematical Handling by Modulo

Time Complexity: O(n * log(max(nums[i]))), where n is the number of elements and max(nums[i]) is the maximum number in nums. Space Complexity: O(1).

Simulation–

Complexity analysis

ApproachTimeSpaceWhen to Use
Iterative Digit Extraction to Compute SumsO(n * d)O(1)General case. Clear and easy to implement during interviews.
Mathematical Handling by ModuloO(n * d)O(1)When you want a concise solution that accumulates the difference directly.

Frequently asked questions

Is Difference Between Element Sum and Digit Sum of an Array easy or hard?

This problem is classified as Easy. It mainly tests understanding of array traversal and digit extraction using modulo arithmetic. Most solutions are short and run in O(n) time with constant space.

Difference Between Element Sum and Digit Sum of an Array Python/Java solution

In Python or Java, iterate through the array, accumulate the element sum, and extract digits using modulo and division inside a loop. The logic is identical across languages because it relies only on basic arithmetic operations and simple iteration.

How to solve Difference Between Element Sum and Digit Sum of an Array in O(n)?

Traverse the array once while maintaining two running totals: element sum and digit sum. Extract digits from each number using modulo (num % 10) and division (num /= 10). After processing all elements, return the absolute difference between the two sums. This effectively runs in linear time with constant space.

What is the best approach for Difference Between Element Sum and Digit Sum of an Array?

The standard approach iterates through the array and extracts digits using modulo operations. For each number, add the full value to the element sum and repeatedly use num % 10 and num / 10 to accumulate the digit sum. This runs in O(n * d) time where d is the number of digits per element and uses O(1) extra space.

Is Difference Between Element Sum and Digit Sum of an Array asked at Google/Amazon/Meta?

Problems involving digit extraction and arithmetic manipulation appear frequently in coding interviews at large tech companies. While this exact problem is relatively simple, similar number-processing questions are common screening exercises used by companies like Amazon and Google.

What data structure is used in Difference Between Element Sum and Digit Sum of an Array?

The primary data structure is a simple array traversal. The algorithm does not require additional structures like hash maps or stacks. It relies mainly on arithmetic operations such as modulo and integer division.

What is the time complexity of Difference Between Element Sum and Digit Sum of an Array?

The time complexity is O(n * d). The algorithm iterates through n numbers in the array, and for each number processes its digits individually. Since integers have a limited number of digits, this behaves close to O(n) in practice.

Comments

Now write it yourselfClose this page and solve Difference Between Element Sum and Digit Sum of an Array in the editor, without looking.
Practise Difference Between Element Sum and Digit Sum of an Array