Difference between element sum and digit sum of an array
January 15, 2023
array-and-hashmapProblem URL: Difference between element sum and digit sum of an array
We will calculate the sum of every digit in the array and subtract it from the sum of the array.
class Solution:
def differenceOfSum(self, nums: List[int]) -> int:
numsArrayAsString = list(''.join(map(str, nums)))
numsArrayDigits = list(map(int, numsArrayAsString))
digitSum = sum(numsArrayDigits)
elementSum = sum(nums)
return elementSum - digitSum
Time complexity: O(n)
Space complexity: O(n)
We can achieve the same result with a single line.
class Solution:
def differenceOfSum(self, nums: List[int]) -> int:
return sum(nums) - sum(map(int, list(''.join(map(str, nums)))))