Problem 2535

Abstract / Summary

Calculate the total of all numbers in the array and subtract the total of all their digits to find the difference.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 2535.py

class Solution:
    def differenceOfSum(self, nums: List[int]) -> int:
        element = sum(nums)
        digit = 0
        for i in nums:
            while i > 0:
                digit += i % 10
                i //= 10

        return element - digit
10 lines | 264 bytes | submitted August 15, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 85% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution class implements a single method differenceOfSum. The method receives a list of integers, computes the sum of the integers themselves, computes the sum of all decimal digits that appear in those integers, and returns the arithmetic difference between the two sums. The implementation relies on Python’s built-in sum for the first aggregation and a manual digit-extraction loop for the second.

Key Steps

Compute the total of the list elements

element = sum(nums)

The built-in sum iterates over nums once, adding each integer to an accumulator. This step yields the aggregate value of the original numbers.

Accumulate the sum of all decimal digits

digit = 0
for i in nums:
    while i > 0:
        digit += i % 10
        i //= 10

A variable digit is initialized to zero. The outer for loop iterates over each integer i in the input list. The inner while loop extracts the least-significant decimal digit with i % 10, adds it to digit, and then discards that digit by integer division i //= 10. The loop continues until i becomes zero, ensuring every digit of a positive integer contributes to the total.

Return the difference between the two sums

return element - digit

The final expression subtracts the accumulated digit sum from the element sum and returns the result.

Edge Cases Handled

When the input list is empty, sum(nums) yields 0, the for loop executes zero times, and digit remains 0. The method therefore returns 0, correctly reflecting the difference of two empty aggregations.

If an element in the list is 0, the inner while condition i > 0 is false on the first check, so no digit is added. Since the decimal representation of 0 contains a single digit 0, the contribution to the digit sum is correctly 0.

For very large positive integers, the digit extraction loop processes each decimal digit individually without converting the number to a string, avoiding the overhead of temporary string objects and preserving numeric precision.

Negative numbers are effectively ignored by the digit-extraction loop because the condition i > 0 fails immediately. Consequently, their digits do not contribute to the digit sum, which aligns with the algorithm’s implicit assumption that only non-negative digits are considered.

Performance Optimizations

The use of the built-in sum function for the element aggregation leverages CPython’s highly optimized C implementation, providing fast linear traversal of the input list.

Digit extraction is performed with pure integer arithmetic (% and //). This avoids the creation of intermediate string representations, which would incur additional memory allocation and processing time. The loop processes each digit in constant time, resulting in a tight inner loop that benefits from CPU cache locality.

By reusing the loop variable i for digit extraction, the code avoids allocating extra temporary variables, keeping the memory footprint minimal. The overall structure ensures a single pass over the list for the element sum and a second pass that touches each digit exactly once, delivering efficient execution for typical input sizes.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a box full of number blocks. This code starts by adding up the value of every single whole block you have in the box. After that, it looks at each block again to see which individual digits are written on them, like if there is a number twelve, it looks at the one and the two separately. It adds all those little digits together into a new pile. Finally, it takes the big pile of whole blocks and takes away the pile of tiny number digits to see what is left over.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.69 | σ = 1.61

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Python Java C++ TS
WalkCCC Python Java C++
leetcode.ca Python Java Go C++ C Rust TS
Progiez Python Java C++
github chandansgowda Python
charles-wangkai Java
fartem Ruby
fsq C++
JoshCrozier JS
lkwq007 Python
muhammadfarhankt Go
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
chandansgowda Python
charles-wangkai Java
fartem Ruby
fsq C++
JoshCrozier JavaScript
lkwq007 Python
muhammadfarhankt Go
varunu28 Java
25 links | 12 authors | 9 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

30 solutions   August 15, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality