![]() |
VOOZH | about |
Given a number n, count the numbers from 1 to n, which comprise only digits from set {1, 2, 3, 4, 5}.
Examples:
Input: n = 20
Output: 10
Explanation: The numbers whose digits are from the given set are: 1, 2, 3, 4, 5, 11, 12, 13, 14, 15. There are 10 such numbers.
Input: n = 100
Output: 30
Explanation: The numbers whose digits are only from the set are: 1, 2, 3, 4, 5, 11, 12, 13, 14, 15, 21, 22, 23, 24, 25, 31, 32, 33, 34, 35, 41, 42, 43, 44, 45, 51, 52, 53, 54, 55. There are 30 such numbers.
Table of Content
The idea is to iterate through all numbers from 1 to n and check whether each digit of the current number belongs to the set {1, 2, 3, 4, 5}. If all digits are valid, increment the count.
30
Time Complexity: O(n * log n)
Auxiliary Space: O(1)
The idea is to generate only those numbers whose digits belong to the set {1, 2, 3, 4, 5} instead of checking every number from 1 to n. Start with the one-digit numbers 1, 2, 3, 4, 5 in a queue. Repeatedly remove a number from the queue, count it if it is not greater than n, and append digits 1, 2, 3, 4, 5 to generate new valid numbers. This performs a BFS over all valid numbers and avoids examining invalid ones.
30
Time Complexity: O(k), where k is the number of valid numbers generated.
Auxiliary Space: O(k)