Call a number self-dividing when each of its digits divides it with no remainder. For example, 36 qualifies: both 3 and 6 go into 36 evenly. A number with a 0 among its digits never qualifies, since you cannot divide by zero.
Given two whole numbers left and right, return every self-dividing number from left to right, both ends included, in increasing order.
Example 1
Input: left = 10, right = 16 Output: [11, 12, 15] Why: 10 has a 0; 13, 14 and 16 each have a digit that leaves a remainder
2 more examples and the constraints
Example 2
Input: left = 30, right = 40 Output: [33, 36] Why: 3 divides 33; 3 and 6 both divide 36
Example 3
Input: left = 101, right = 109 Output: [] Why: every number from 101 to 109 contains a 0
Constraints
- 1 ≤ left ≤ right ≤ 10,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check the digits as textO(n·d)
- Peel digits with % 10O(n·d)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 numbers | Verdict |
|---|---|---|---|
| Check the digits as text | O(n·d) | Clear; builds a string per number | |
| Peel digits with % 10 | O(n·d) | Best; arithmetic only |
n = right − left + 1, d = digits per number (at most 5).
Edge cases to test
- A zero digit. 10, 20, 101: a 0 anywhere means the number is out, and you must not divide by it.
- Single digits. Every number from 1 to 9 divides itself, so all of them qualify.
- left equals right. left = right = 15 gives [15]; left = right = 16 gives [].
- Upper limit. 10,000 has zeros, so it is never in the answer; 9,999 is.
- Nothing qualifies. 101 to 109 gives an empty list.
Common mistakes
- Dividing by a 0 digit instead of rejecting the number first.
- Checking the digit against the shrinking x instead of the original n.
- Stopping the range one short of
right, which is included.
How to talk through it
- 1Clarify. Are both ends included? Should the list be in increasing order?
- 2Size the work. At most 10,000 numbers with 5 digits each: a plain scan is about 50,000 checks.
- 3Pick the digit trick.
% 10reads the last digit,// 10drops it; no string needed. - 4Code the check. Stop on a 0 digit or a remainder; keep n only when x reached 0.
- 5Test out loud. Run 10, 15, 22 and 9,999 to check zeros, single passes and the top of the range.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?