VOOZH about

URL: https://www.geeksforgeeks.org/dsa/numbers-from-1-to-n-with-digits-in-set-1-2-3-4-5/

⇱ Numbers from 1 to n with digits in set {1, 2, 3, 4, 5} - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Numbers from 1 to n with digits in set {1, 2, 3, 4, 5}

Last Updated : 4 Jun, 2026

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.

Check Every Number - O(n * log n) Time O(1) Space

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.


Output
30

Time Complexity: O(n * log n)
Auxiliary Space: O(1)

Generate Only Valid Numbers - (k) Time O(k) Space

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.


Output
30

Time Complexity: O(k), where k is the number of valid numbers generated.
Auxiliary Space: O(k)

Comment
Article Tags:
Article Tags: