![]() |
VOOZH | about |
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.
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.
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:
Below is the implementation of the above approach:
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: