Difference Between Element Sum and Digit Sum of an Array Problem
#2535
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2535.
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 <= 20001 <= nums[i] <= 2000
Solution
Approach: Direct Simulation
Walk through the array once, keeping the sum of the elements x and the sum of all their digits y. Each digit sum is at most the number itself, so x - y is never negative and we can return it without an absolute value.
Complexity: O(n log M) time, where M is the largest value (each number has about log M digits), and O(1) extra space.
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