Difference Between Element Sum and Digit Sum of an Array — LeetCode 2535 Python Solution

EasyArrayMath
Problem
#2535
Reading time
2 min

The problem

You are given a positive integer array nums. The element sum is the sum of all the elements in nums.

Example

Input
nums = [1,15,6,3]
Output
9
Explanation
The element sum of nums is 1 + 15 + 6 + 3 = 25.

Python solution

Python
class Solution:
    def differenceOfSum(self, nums: List[int]) -> int:
        x = y = 0
        for v in nums:
            x += v
            while v:
                y += v % 10
                v //= 10
        return x - y

Complexity

MeasureComplexity
TimeO(n \times \log_{10} M), where n and M are the length of the array \textit{nums} and the maximum value of the elements in the array, respectively
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2535. Difference Between Element Sum and Digit Sum of an Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2535. Difference Between Element Sum and Digit Sum of an Array?
LeetCode 2535. Difference Between Element Sum and Digit Sum of an Array is rated Easy on LeetCode.
What is the time complexity of LeetCode 2535. Difference Between Element Sum and Digit Sum of an Array?
The Python solution on this page runs in O(n \times \log_{10} M), where n and M are the length of the array \textit{nums} and the maximum value of the elements in the array, respectively.
What is the space complexity of LeetCode 2535. Difference Between Element Sum and Digit Sum of an Array?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2535. Difference Between Element Sum and Digit Sum of an Array cover?
LeetCode 2535. Difference Between Element Sum and Digit Sum of an Array is tagged Array and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview