EasyNo. 2535

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

Topics
Array, Math
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

PythonSolution
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

Time
O(n × 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
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
0048Rotate ImageMedium
0066Plus OneEasy
0189Rotate ArrayMedium
0204Count PrimesMedium
0335Self CrossingHard
0384Shuffle an ArrayMedium

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 × 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.

Free to download. Check it runs on your machine, then pick a plan.