Self Dividing Numbers — LeetCode 728 Python Solution

EasyMath
Problem
#728
Reading time
2 min

The problem

A self-dividing number is a number that is divisible by every digit it contains. For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.

Example

Input
left = 1, right = 22
Output
[1,2,3,4,5,6,7,8,9,11,12,15,22]

Python solution

Python
class Solution:
    def selfDividingNumbers(self, left: int, right: int) -> List[int]:
        def check(x: int) -> bool:
            y = x
            while y:
                if y % 10 == 0 or x % (y % 10):
                    return False
                y //= 10
            return True

        return [x for x in range(left, right + 1) if check(x)]

Complexity

MeasureComplexity
TimeO(n \times \log_{10} M), where n is the number of elements in the interval [\textit{left}, \textit{right}], and M = \textit{right}, which is the maximum value in the interval
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 728. Self Dividing Numbers is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 728. Self Dividing Numbers?
LeetCode 728. Self Dividing Numbers is rated Easy on LeetCode.
What is the time complexity of LeetCode 728. Self Dividing Numbers?
The Python solution on this page runs in O(n \times \log_{10} M), where n is the number of elements in the interval [\textit{left}, \textit{right}], and M = \textit{right}, which is the maximum value in the interval.
What is the space complexity of LeetCode 728. Self Dividing Numbers?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 728. Self Dividing Numbers cover?
LeetCode 728. Self Dividing Numbers is tagged Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview