VOOZH about

URL: https://www.geeksforgeeks.org/dsa/total-numbers-no-repeated-digits-range/

⇱ Total numbers with no repeated digits in a range - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Total numbers with no repeated digits in a range

Last Updated : 8 May, 2023

Given a range find total such numbers in the given range such that they have no repeated digits. For example: 12 has no repeated digit. 22 has repeated digit. 102, 194 and 213 have no repeated digit. 212, 171 and 4004 have repeated digits. 

Examples: 

Input : 10 12
Output : 2
Explanation : In the given range 
10 and 12 have no repeated digit 
where as 11 has repeated digit.

Input : 1 100
Output : 90

Brute Force We will traverse through each element in the given range and count the number of digits which do not have repeated digits. 


Output
90

This method will answer each query in O( N ) time. 

Auxiliary Space: O(log(N))

Efficient Approach

We will calculate a prefix array of the numbers which have no repeated digit. = Total number with no repeated digit less than or equal to 1. Therefore each query can be solved in O(1) time. 

Below is the implementation of above idea.


Output
90

Efficient Approach:  The above approach can be optimized based on the following idea:

Dynamic programming can be used to solve this problem

  • dp[i][j][k][l] represents numbers in the range with i'th position to be filled, j represents tight condition, k represents bitmask set for each digit from 0 to 9 and l represents whether previously non zero digit number taken or not. 
     
  • It can be observed that the recursive function is called exponential times. That means that some states are called repeatedly. 
    So the idea is to store the value of each state. This can be done using by store the value of a state and whenever the function is called, return the stored value without computing again.
     
  • First answer will be calculated for 0 to A - 1 and then calculated for 0 to B then latter one is subtracted with prior one to get answer for range [L, R]

Follow the steps below to solve the problem:

  • Create a recursive function that takes four parameters i representing the position to be filled, j representing the tight condition, k representing bitmask and l representing whether previously non zero digit taken or not.
  • Call the recursive function for choosing all digits from 0 to 9 apart from N.
  • Base case if N size digit formed return 1;
  • Create a 2d array dp[N][2][M][2] initially filled with -1.
  • If the answer for a particular state is computed then save it in dp[i][j][k][l].
  • If the answer for a particular state is already computed then just return dp[i][j][k][l].

Below is the implementation of the above approach:


Output
90

Time Complexity: O(log(R - L) * M) 
Auxiliary Space: O(log(R - L) * M)

Where M is the all possible subsets of set containing all digits from 0 to 9 for bitmask M = 1024  

Related Articles:

Comment