3622. Check Divisibility by Digit Sum and Product
ā Runtime tested ā the solution passes every example case. š Full written solution: https://interview-kit-fe.vercel.app/check-divisibility-by-digit-sum-and-product š» Code on GitHub: https://github.com/timepasshub2539-hue/leetcode-python/tree/main/check-divisibility-by-digit-sum-and-product Chapters: 0:00 Why 84 Divides By 44 0:18 LeetCode 3622 Overview 0:32 Problem 3622 0:41 Divisibility Rule Explained 1:00 Tracing Example 99 1:20 Problem Constraints 1:36 Solution Plan 1:54 Zero Digit Edge Case 2:19 Sum Plus Product 2:37 Extracting Digits 2:52 Combining Sum And Product 3:03 Full Python Solution 3:33 Why The Solution Works 3:46 Edge Cases To Check 4:12 Time And Space Complexity 4:39 Proof Of Correctness 4:58 Quick Quiz 5:07 Pause And Think 5:09 Quiz Answer 5:16 Round Two Quiz 5:27 Pause And Think 5:30 Quiz Answer 5:40 Divisibility By Digit Sum Recap Walk through LeetCode 3622 step by step: what digit sum + digit product divisibility actually asks, why 84 divides evenly by 44, and how a zero digit changes the math. We trace the logic by hand on 99, build the full Python solution one digit-peel at a time, then prove correctness and check edge cases and time/space complexity. Two quick quizzes along the way to test your understanding before the recap. #leetcode #python #coding #dsa #programming Watch next: - 3 Checks Find The Bug In 500 Lines #shorts: https://youtu.be/3BDvBdfU6SM - Python Lesson 30: Why Does print() Stop Working in Production?: https://youtu.be/vr_iIXguEyM - The Problem: Smallest Divisible Digit Product II #shorts: https://youtu.be/eFtoVxi_5cM
Introduction
Digit-manipulation problems show up constantly in coding interviews because they test something narrower and more useful than clever algorithms: can you carefully translate a plain-English rule into precise arithmetic without introducing bugs along the way? LeetCode 3622, Check Divisibility by Digit Sum and Product, is exactly this kind of problem. The algorithm itself is simple ā you will not need a single advanced data structure ā but the problem rewards engineers who read the rule carefully instead of skimming it and guessing.
That distinction matters in interviews. A candidate who jumps straight to code often builds something that only handles the "obvious" case, then stumbles when a zero digit or a single-digit input breaks their assumptions. This problem is a good filter for exactly that habit, which is why it's worth understanding deeply rather than just memorizing the solution.
Problem Overview
You're given a positive integer n. Break n into its individual digits. Compute two values from those digits:
- Digit sum ā add every digit together.
- Digit product ā multiply every digit together.
Add the digit sum and the digit product into one combined total. Then check whether n divides evenly into that total. If there's no remainder, return true. Otherwise, return false.
The key detail ā and the one people misread ā is that you don't check divisibility against the sum alone, or the product alone. You check it against the sum of the two, computed once, checked once.
Example
Take n = 99. Its digits are 9 and 9.
- Digit sum:
9 + 9 = 18 - Digit product:
9 Ć 9 = 81 - Combined total:
18 + 81 = 99 - Check:
99 % 99 == 0ātrue
It's a satisfying example because the combined total lands exactly back on n, but don't let that coincidence suggest the two pieces are interchangeable. Neither 18 nor 81 divides 99 on its own ā only the sum of the two does. That's the rule in action, not a shortcut around it.
A second example makes the "zero digit" case concrete: n = 105. Digits are 1, 0, 5.
- Digit sum:
1 + 0 + 5 = 6 - Digit product:
1 Ć 0 Ć 5 = 0 - Combined total:
6 + 0 = 6 - Check:
105 % 6 = 3āfalse
The zero digit didn't break anything ā it just zeroed out the product's contribution, leaving the sum to carry the check on its own.
Intuition
The first thing an experienced engineer does with a problem like this is separate what's fixed from what's computed. n is fixed ā you're not allowed to change it. What you're computing is a single number (sum + product) built entirely from n's own digits, and then you're asking a basic divisibility question about it.
That reframing immediately tells you the shape of the solution: this is a single pass over the digits of n, accumulating two running values, followed by one final check. There's no need to store the digits in a list, reverse a string, or recurse ā you just need two accumulators and a loop.
The next thing worth noticing, before writing any code, is a boundary case that trips people up: what if a digit is 0? Some engineers reflexively add a guard ā "if the digit is zero, skip updating the product, because multiplying by zero would ruin everything." But look at what's actually being divided: it's the sum of digit sum and digit product, not the product by itself. Since n is a positive number, it has at least one digit, and the digit sum of a positive number's digits is always at least 1. So even if the product collapses entirely to zero, the sum keeps the combined total above zero. No defensive check needed ā the math already handles it.
This is a useful habit to build: before adding a guard clause, ask whether the guard is protecting against something that can actually happen given the other constraints of the problem. Here it can't, so the guard would just be unnecessary code.
Brute Force Solution
There isn't really a slower alternative here worth calling "brute force" in the traditional sense ā this problem doesn't have a naive recursive or exponential approach to avoid. The one variant worth mentioning is converting n to a string and iterating over its characters instead of peeling digits arithmetically.
Idea: Convert n to a string, iterate over each character, convert each back to an integer, and accumulate sum and product.
Advantages: Slightly more readable to some engineers; avoids manual % 10 / // 10 arithmetic.
Disadvantages: String conversion and repeated int() casting add overhead that's completely unnecessary given how easy digit extraction is with arithmetic. It also encourages a habit ā reaching for string conversion by default ā that doesn't generalize well to problems with larger numeric constraints.
Time complexity: O(d) where d is the number of digits.
Space complexity: O(d) for the string representation.
The arithmetic approach below has the same time complexity but true O(1) space, so it's the better default.
Optimal Solution
The optimal approach processes n's digits one at a time using two well-worn tools:
n % 10gives you the last digit.n // 10drops that last digit (integer division).
You keep a running sum (starting at 0) and a running product (starting at 1, since multiplying by zero at the start would erase everything). On each loop iteration:
- Extract the last digit with
% 10. - Add it to
sum. - Multiply it into
product. - Shrink the working number with
// 10.
The loop ends when the working number reaches 0 ā every digit has been visited exactly once. At that point, add sum and product together and check n % (sum + product) == 0.
| Step | temp | digit | sum | product |
|---|---|---|---|---|
| start | 99 | ā | 0 | 1 |
| 1 | 9 | 9 | 9 | 9 |
| 2 | 0 | 9 | 18 | 81 |
After the loop: sum + product = 99, and 99 % 99 == 0 ā true.
Note that we work on a copy of n (call it temp) rather than mutating n itself, since the original value of n is needed for the final divisibility check.
Python Code
def check_divisibility(n: int) -> bool:
"""Return True if n is divisible by (digit sum + digit product) of n."""
digit_sum = 0
digit_product = 1
temp = n
while temp > 0:
digit = temp % 10
digit_sum += digit
digit_product *= digit
temp //= 10
total = digit_sum + digit_product
return n % total == 0
Code Walkthrough
digit_sum = 0: additive identity ā the starting point for a running sum.digit_product = 1: multiplicative identity ā starting at0would zero out every digit multiplied into it.temp = n: a disposable copy, sincenis needed intact for the final check.while temp > 0: loop continues as long as there are unprocessed digits.digit = temp % 10: extracts the last digit of the currenttemp.digit_sum += digitanddigit_product *= digit: fold the digit into both running accumulators in the same pass.temp //= 10: drops the digit just processed, guaranteeing the loop terminates sincetempshrinks by roughly a factor of 10 each iteration.total = digit_sum + digit_product: the one combination step, performed exactly once.n % total == 0: the one comparison, performed exactly once.
Dry Run
Let's trace n = 84 from the video's opening hook.
| temp | digit | digit_sum | digit_product |
|---|---|---|---|
| 84 | 4 | 4 | 4 |
| 8 | 8 | 12 | 32 |
| 0 | ā | 12 | 32 |
total = 12 + 32 = 44. Check: 84 % 44 = 40 ā not zero ā false.
So despite the video's teaser, 84 does not divide evenly by 44 ā the point of that opening was to get you computing digit sum and digit product by hand, not to claim 84 passes the check.
Complexity Analysis
Time complexity: O(log n), or equivalently O(d) where d is the number of digits in n. Since n ⤠1,000,000, that's at most 7 digits ā the loop runs at most 7 times regardless of the exact value.
Space complexity: O(1). Only a handful of integer variables (digit_sum, digit_product, temp, digit) are used, independent of the size of n.
Both bounds are tight because every digit is visited exactly once, and no auxiliary data structure grows with input size.
Alternative Solutions
The only reasonable alternative is the string-based version described in the brute force section ā converting n to str(n) and iterating over characters with int(ch). It's functionally equivalent and has the same time complexity, but trades O(1) space for O(d) space and adds string/int conversion overhead. For a constraint this small (ā¤7 digits) the performance difference is negligible, but the arithmetic version is the more idiomatic choice for digit-manipulation problems in general, and that habit pays off on problems with much larger digit counts.
Edge Cases
- Single-digit
n(e.g.,n = 7): digit sum and digit product both equal7, so total is14.7 % 14 = 7āfalse. In fact, any single-digit number always produces a total of exactly double itself, so single-digit inputs can never returntrue. ncontaining a zero digit (e.g.,n = 105): the product term vanishes, but the sum still contributes, so the check still runs correctly with no special-casing.- Minimum input,
n = 1: digit sum1, digit product1, total2.1 % 2 = 1āfalse. - Maximum input,
n = 1,000,000: six zero digits collapse the product to0, digit sum is1, total is1.1,000,000 % 1 = 0ātrue. - All digits identical (e.g.,
n = 22): digit sum4, digit product4, total8.22 % 8 = 6āfalse.
Common Mistakes
- Adding a zero-guard for the digit product. As covered above, this is unnecessary ā the sum term guarantees the total is never zero, so there's nothing to divide by zero.
- Checking divisibility against the sum and product separately instead of their combined total. The problem requires one combined check, not two independent ones.
- Initializing
digit_productto0instead of1. This silently zeroes out the entire product on the first multiplication. - Mutating
ndirectly instead of using a copy. Sincenis needed for the final modulo check, tearing it apart in the loop leaves nothing to check against. - Off-by-one errors in the loop condition, such as using
while temp >= 0, which causes an infinite loop or an extra spurious "digit" of0. - Forgetting to handle the loop when
nitself is single-digit, assuming the while loop needs at least two iterations to function correctly (it doesn't ā one iteration handles it fine).
Interview Questions
- What would you need to change if
ncould be negative? - How would your solution change if you needed the digit count as well as sum and product?
- Can this be solved recursively instead of iteratively? What are the tradeoffs?
- How would you adapt this if the base were not 10 (e.g., digit sum/product in base 16)?
- What's the largest
nfor which digit_product could overflow in a language without arbitrary-precision integers, and how would you defend against that?
Similar Problems
- LeetCode 1281 ā Subtract the Product and Sum of Digits of an Integer: nearly identical digit extraction logic, just a different final combination step.
- LeetCode 258 ā Add Digits: repeatedly sums digits until a single digit remains, reinforcing the peel-and-shrink pattern.
- LeetCode 2520 ā Count the Digits That Divide a Number: same digit-peeling loop, different per-digit check.
- LeetCode 9 ā Palindrome Number: uses the same
% 10/// 10mechanics to process digits without converting to a string. - LeetCode 231 ā Power of Two: not digit-based, but a good companion problem for practicing "check a numeric property, then compare once" reasoning.
Key Takeaways
Digit-manipulation problems live and die on careful reading, not clever algorithms. The pattern here ā peel with % 10, shrink with // 10, accumulate as you go, combine and compare exactly once ā generalizes to a huge class of interview problems. The real skill being tested isn't the loop; it's resisting the urge to add unnecessary guards for cases the math already rules out, and resisting the urge to combine values in ways the problem statement didn't actually ask for.
Watch the Video
Prefer to see this traced by hand, digit by digit, with the two quick quizzes included? Watch the full walkthrough here: {LINK}
About the Series
This breakdown is part of Fun with Learning Technology, a series focused on making coding interview problems and core computer science concepts genuinely click ā not just memorized, but understood well enough to explain to someone else. Every episode builds intuition first and code second, because that order is what actually sticks in an interview room.
Call To Action
If this walkthrough helped the logic click, the biggest favor you can do is like the video on YouTube and subscribe ā it directly helps more developers find these breakdowns. For deeper dives delivered straight to your inbox, subscribe to the Substack newsletter. And if you spotted a cleaner approach or a case this didn't cover, drop it in the comments ā sharing this with someone prepping for interviews helps them too.
The solution
class Solution:
def checkDivisibility(self, n: int) -> bool:
total_sum = 0
total_product = 1
temp = n
while temp > 0:
d = temp % 10
total_sum += d
total_product *= d
temp //= 10
return n % (total_sum + total_product) == 0Ready to try it yourself? Solve General problems with instant feedback in the practice sandbox.
Practice now ā


