Problem 1281

Abstract / Summary

Given an integer, find the difference between the product of its digits and the sum of its digits.

Note

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

Python 1281.py

class Solution:
    def subtractProductAndSum(self, n: int) -> int:
        digits = [ int(d) for d in str(n) ]
        return reduce(mul, digits) - reduce(add, digits)
4 lines | 173 bytes | submitted December 1, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 87% (500k+ submissions).

Typical patterns to solve this problem:
  • 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 implementation defines a single method subtractProductAndSum that receives an integer n and returns the difference between the product of its decimal digits and the sum of those same digits. The algorithm follows a straightforward pipeline: convert the integer to its string representation, extract each character as an integer digit, compute the product of all digits, compute the sum of all digits, and finally subtract the sum from the product.

Digit Extraction

The first logical step isolates the individual decimal digits of the input number.

digits = [int(d) for d in str(n)]

By casting n to a string, each character corresponds to a single digit. The list comprehension iterates over the characters, converting each back to an integer. This approach automatically handles any non-negative integer, including the special case where n is a single-digit number; the resulting list will contain exactly one element, and the subsequent product and sum operations will work without additional branching.

Product Computation

The product of the extracted digits is obtained with the reduce function combined with the multiplication operator.

product = reduce(mul, digits)

reduce applies mul cumulatively to the items of digits, producing a single integer that represents the product. Because reduce processes the list in a left-to-right fashion, the order of multiplication does not affect the result, and the implementation naturally accommodates the edge case where any digit is zero-the product becomes zero immediately without extra checks.

Sum Computation

Similarly, the sum of the digits is calculated using reduce with the addition operator.

total = reduce(add, digits)

This reduces the list to the arithmetic sum of its elements. For a single-digit input, the sum equals the digit itself, and the subtraction later yields zero, which matches the mathematical expectation for that scenario.

Final Result

The method returns the difference between the product and the sum.

return product - total

Because both product and total are already computed, the subtraction is a constant-time operation. The overall flow ensures that the function delivers the correct mathematical result for any non-negative integer, including zero, where the digit list becomes [0], the product is 0, the sum is 0, and the final result is 0.

Edge Cases Handled

When n equals 0, the string conversion yields "0" and the list comprehension produces [0]. The multiplication of a single zero yields 0, and the addition also yields 0; the subtraction therefore returns 0. For numbers containing one or more zero digits, the product collapses to 0 as soon as the zero is encountered during reduction, while the sum still reflects the contribution of the remaining digits. Single-digit inputs result in identical product and sum values, leading to a zero difference, which aligns with the definition of the operation.

Performance Optimizations

The code leverages built-in Python constructs that are implemented in C for speed. Converting the integer to a string and iterating with a list comprehension is faster than manual arithmetic extraction of digits using division and modulo operations. The use of reduce together with the operator.mul and operator.add functions avoids the overhead of Python-level loops and function calls for each arithmetic step. By delegating the aggregation to these highly optimized primitives, the implementation minimizes interpreter overhead and benefits from the underlying C loops, resulting in efficient execution even for numbers with many digits.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big number, like a secret password made of digits. This code acts like a little robot that takes that number apart to look at each digit one by one. First, it peeks at every single digit acting like a tiny brick in a tower. Once it has all those separate bricks, it does two special math games. In the first game, it multiplies all the bricks together to get one big pile. In the second game, it adds all those same bricks together to get a different pile. Finally, it takes the big multiplication pile and takes away the addition pile to see what is left over. It is just like playing with building blocks to solve a fun math puzzle.

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.19 | σ = 2.27

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 C++ Java TS
WalkCCC Python C++ Java
leetcode.ca Python C++ Java Go C# C Rust TS
Progiez Python C++ Java
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
Garvit244 Python
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C
lkwq007 Python
muhammadfarhankt Go
pruthvikp Python
suxrobGM C#
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, C#, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
Garvit244 Python
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C
lkwq007 Python
muhammadfarhankt Go
pruthvikp Python
suxrobGM C#
varunu28 Java
36 links | 22 authors | 10 languages

Videos

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

Solved On The Same Day

6 solutions   December 1, 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