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
Difficulty
and has an acceptance rate of about 85% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Math
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
Other Solutions
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 |
Videos
Similar Problems
- problem 2160: Minimum Sum of Four Digit Number After Splitting Digits
Solved On The Same Day
- problem 112: Path Sum
- problem 409: Longest Palindrome
- problem 645: Set Mismatch
- problem 717: 1-bit and 2-bit Characters
- problem 16: 3Sum Closest
- problem 24: Swap Nodes in Pairs
- problem 113: Path Sum II
- problem 114: Flatten Binary Tree to Linked List
- problem 116: Populating Next Right Pointers in Each Node
- problem 129: Sum Root to Leaf Numbers
- problem 131: Palindrome Partitioning
- problem 137: Single Number II
- problem 162: Find Peak Element
- problem 165: Compare Version Numbers
- problem 172: Factorial Trailing Zeroes
- problem 201: Bitwise AND of Numbers Range
- problem 204: Count Primes
- problem 402: Remove K Digits
- problem 430: Flatten a Multilevel Doubly Linked List
- problem 451: Sort Characters By Frequency
- problem 539: Minimum Time Difference
- problem 583: Delete Operation for Two Strings
- problem 633: Sum of Square Numbers
- problem 648: Replace Words
- problem 650: 2 Keys Keyboard
- problem 670: Maximum Swap
- problem 786: K-th Smallest Prime Fraction
- problem 2507: Smallest Value After Replacing With Sum of Prime Factors
- problem 2523: Closest Prime Numbers in Range
Extra
- 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