Subtract the Product and Sum of Digits of an Integer solution and explanation
9 more videos on this problem
LeetCode 1281: Subtract the Product and Sum of Digits of Integer - Interview Prep Ep 25Fisher Coder · 6:19 · 3K views
Leetcode Solution - 1281 Subtract the Product and Sum of Digits of an IntegerJohn Leonardo · 2:16 · 954 views
Subtract the Product and Sum of Digits of an Integer | LeetCode 1281 | CppCodeClips with Abhishek Ranjan · 4:21 · 848 views
LeetCode #1281. Subtract the Product and Sum of Digits of an Integer | JavascriptDarwin Tech · 3:23 · 654 views
Subtract the Product and Sum of Digits of an Integer | Leetcode 1281 | Top interview questionSuper Lazy Coder · 4:14 · 568 views
LeetCode - Subtract the Product and Sum of Digits of an Integer in PythonKnowledge Mavens · 5:18 · 529 views
Leetcode 1281: Subtract the Product and Sum of Digits of an IntegerAlgorithms Casts · 8:57 · 523 views
Leetcode 1281 - Subtract the Product and Sum of Digits of an Integer (Beats 100% of the solutions)Faceless Engineer · 8:41 · 380 views
LeetCode 1281: Subtract The Product And Sum of Digits of an Integer (SOLVED)Michael Vandi · 14:58 · 338 views
Leetcode 1281. Subtract the Product and Sum of Digits of an Integer Python SolutionTechZoo · 2:30 · 322 views
The problem
n, return the difference between the product of its digits and the sum of its digits.
Example 1:
Input: n = 234 Output: 15 Explanation: Product of digits = 2 * 3 * 4 = 24 Sum of digits = 2 + 3 + 4 = 9 Result = 24 - 9 = 15
Example 2:
Input: n = 4421 Output: 21 Explanation: Product of digits = 4 * 4 * 2 * 1 = 32 Sum of digits = 4 + 4 + 2 + 1 = 11 Result = 32 - 11 = 21
Constraints:
1 <= n <= 10^5
Approach overview
Problem Overview: You are given an integer n. Compute the product of its digits and the sum of its digits, then return product - sum. The task mainly tests basic math operations and how you extract digits from a number.
Approach 1: Loop Through Digits (O(d) time, O(1) space)
This is the standard mathematical approach. Repeatedly extract the last digit using n % 10, update both the running product and running sum, and then remove the digit with integer division n // 10. Continue until the number becomes zero. Each iteration processes one digit, so the total work is proportional to the number of digits d.
The key idea is that modulus gives the current digit and division shifts the number right by one decimal place. This avoids converting the number to another data type and keeps memory usage constant. The algorithm performs simple arithmetic operations while iterating through digits, making it both efficient and easy to reason about. Time complexity is O(d) and space complexity is O(1).
This pattern appears frequently in math and simulation problems where you need to process digits individually.
Approach 2: String Conversion (O(d) time, O(d) space)
Another option converts the integer into a string and iterates over its characters. For each character, convert it back to a digit and update the product and sum variables. This method removes the need for modulus and division operations, which some developers find easier to read.
The logic becomes straightforward: iterate through the string, compute digit = ch - '0' (or equivalent conversion), multiply it into the product, and add it to the sum. Because the string representation stores all digits, this approach requires O(d) additional space. Time complexity remains O(d) since every digit is processed once.
This method is often used when working with string manipulation or when consistency with other string-based operations matters.
Recommended for interviews: The loop-through-digits math approach is what interviewers usually expect. It demonstrates comfort with digit extraction using modulus and division, a common pattern in integer manipulation problems. The string approach still works and is readable, but it adds unnecessary space usage. Showing the math-based method signals stronger problem-solving fundamentals.
Approach 1: Loop through Digits Approach
This approach involves extracting each digit by using modulus and division operations. We'll calculate the product and sum of digits by iterating through the digits.
def subtractProductAndSum(n: int) -> int:
product = 1
sum_digits = 0
while n > 0:
digit = n % 10
product *= digit
sum_digits += digit
n //= 10
return product - sum_digits
print(subtractProductAndSum(234))public class Solution {
public int subtractProductAndSum(int n) {
int product = 1, sum = 0;
while (n > 0) {
int digit = n % 10;
product *= digit;
sum += digit;
n /= 10;
}
return product - sum;
}
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.subtractProductAndSum(234));
}
}#include <iostream>
int subtractProductAndSum(int n) {
int product = 1, sum = 0;
while (n > 0) {
int digit = n % 10;
product *= digit;
sum += digit;
n /= 10;
}
return product - sum;
}
int main() {
int n = 234;
std::cout << subtractProductAndSum(n) << std::endl;
return 0;
}function subtractProductAndSum(n) {
let product = 1, sum = 0;
while (n > 0) {
let digit = n % 10;
product *= digit;
sum += digit;
n = Math.floor(n / 10);
}
return product - sum;
}
console.log(subtractProductAndSum(234));#include <stdio.h>
int subtractProductAndSum(int n) {
int product = 1, sum = 0;
while (n > 0) {
int digit = n % 10;
product *= digit;
sum += digit;
n /= 10;
}
return product - sum;
}
int main() {
int n = 234;
printf("%d\n", subtractProductAndSum(n));
return 0;
}using System;
public class Solution {
public int SubtractProductAndSum(int n) {
int product = 1, sum = 0;
while (n > 0) {
int digit = n % 10;
product *= digit;
sum += digit;
n /= 10;
}
return product - sum;
}
public static void Main() {
Solution s = new Solution();
Console.WriteLine(s.SubtractProductAndSum(234));
}
}Digits are processed using integer operations in a loop. The product and sum of the digits are calculated and returned as their difference.
Time Complexity: O(d), as we loop through each digit.
Space Complexity: O(1).
Approach 2: String Conversion Approach
Convert the number to a string, then iterate through each character, parsing it back to an integer to compute the product and sum of the digits.
def subtractProductAndSum(n: int) -> int:
str_n = str(n)
product = 1
sum_digits = 0
for char in str_n:
digit = int(char)
product *= digit
sum_digits += digit
return product - sum_digits
print(subtractProductAndSum(234))public class Solution {
public int subtractProductAndSum(int n) {
String str = Integer.toString(n);
int product = 1, sum = 0;
for (char c : str.toCharArray()) {
int digit = c - '0';
product *= digit;
sum += digit;
}
return product - sum;
}
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.subtractProductAndSum(234));
}
}#include <iostream>
#include <string>
int subtractProductAndSum(int n) {
std::string str = std::to_string(n);
int product = 1, sum = 0;
for (char c : str) {
int digit = c - '0';
product *= digit;
sum += digit;
}
return product - sum;
}
int main() {
int n = 234;
std::cout << subtractProductAndSum(n) << std::endl;
return 0;
}function subtractProductAndSum(n) {
let str = n.toString();
let product = 1, sum = 0;
for (let char of str) {
let digit = parseInt(char);
product *= digit;
sum += digit;
}
return product - sum;
}
console.log(subtractProductAndSum(234));#include <stdio.h>
#include <string.h>
int subtractProductAndSum(int n) {
char str[6];
sprintf(str, "%d", n);
int product = 1, sum = 0;
for (int i = 0; i < strlen(str); i++) {
int digit = str[i] - '0';
product *= digit;
sum += digit;
}
return product - sum;
}
int main() {
int n = 234;
printf("%d\n", subtractProductAndSum(n));
return 0;
}using System;
public class Solution {
public int SubtractProductAndSum(int n) {
string str = n.ToString();
int product = 1, sum = 0;
foreach (char c in str) {
int digit = c - '0';
product *= digit;
sum += digit;
}
return product - sum;
}
public static void Main() {
Solution s = new Solution();
Console.WriteLine(s.SubtractProductAndSum(234));
}
}Transforms the number to a string, allowing individual digit access, parsed back to integers for computations.
Time Complexity: O(d).
Space Complexity: O(d).
Approach 3: Simulation
We use two variables x and y to record the product of the digits and the sum of the digits respectively. At the beginning, x=1,y=0.
When n \gt 0, each time we take the mod of n by 10 to get the current digit v, and continue the next loop by dividing n by 10. In each loop, we update x = x times v, y = y + v.
Finally, we return x - y.
The time complexity is O(log n), where n is the given integer. The space complexity is O(1).
function subtractProductAndSum(n: number): number {
let [x, y] = [1, 0];
for (; n > 0; n = Math.floor(n / 10)) {
const v = n % 10;
x *= v;
y += v;
}
return x - y;
}func subtractProductAndSum(n int) int {
x, y := 1, 0
for ; n > 0; n /= 10 {
v := n % 10
x *= v
y += v
}
return x - y
}impl Solution {
pub fn subtract_product_and_sum(mut n: i32) -> i32 {
let mut x = 1;
let mut y = 0;
while n != 0 {
let v = n % 10;
n /= 10;
x *= v;
y += v;
}
x - y
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Loop through Digits Approach | Time Complexity: O(d), as we loop through each digit. |
| String Conversion Approach | Time Complexity: O(d). |
| Simulation | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Loop Through Digits (Math) | O(d) | O(1) | Best general solution; minimal memory and standard interview expectation |
| String Conversion | O(d) | O(d) | Useful when already processing digits as strings or prioritizing readability |
Frequently asked questions
Is Subtract the Product and Sum of Digits of an Integer easy or hard?
Subtract the Product and Sum of Digits of an Integer is classified as an Easy problem. It mainly tests basic math operations, loops, and digit extraction. The algorithm is short and typically solved in O(d) time with constant space.
Subtract the Product and Sum of Digits of an Integer Python/Java solution
In Python or Java, iterate through the digits using modulus and division or convert the integer to a string and loop through characters. Maintain two variables: one for the product and one for the sum. After processing all digits, return product - sum.
How to solve Subtract the Product and Sum of Digits of an Integer in O(n)?
Treat n as a number with d digits and iterate through it using modulus and division. At every step, extract the last digit, multiply it into the product, add it to the sum, and remove it from the number. After processing all digits, return product minus sum. This runs in O(d) time and constant space.
What is the best approach for Subtract the Product and Sum of Digits of an Integer?
The most efficient approach iterates through the digits using modulus and division operations. Extract each digit with n % 10, update the running product and sum, and reduce the number using n // 10. This processes each digit exactly once with O(d) time and O(1) space complexity.
Is Subtract the Product and Sum of Digits of an Integer asked at Google/Amazon/Meta?
This problem is categorized as an easy-level math problem and is more common in practice platforms or early interview rounds. Large companies like Google or Amazon typically use it to test basic programming fundamentals such as loops, integer manipulation, and arithmetic operations.
What data structure is used in Subtract the Product and Sum of Digits of an Integer?
No advanced data structures are required. The optimal solution relies on simple integer arithmetic to extract digits. Some implementations optionally convert the number to a string, but the core logic only needs basic variables for the running product and sum.
What is the time complexity of Subtract the Product and Sum of Digits of an Integer?
The time complexity is O(d), where d is the number of digits in the integer. Each digit is processed once while calculating the running product and sum. Space complexity is O(1) when using the mathematical digit extraction approach.
