The Wayback Machine - https://web.archive.org/web/20241002081530/https://www.geeksforgeeks.org/total-numbers-no-repeated-digits-range/
Open In App

Total numbers with no repeated digits in a range

Last Updated : 08 May, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a range L, R                    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. 

C++

// C++ implementation of brute
// force solution.
#include <bits/stdc++.h>
using namespace std;
   
// Function to check if the given
// number has repeated digit or not
int repeated_digit(int n)
{
    unordered_set<int> s;
   
    // Traversing through each digit
    while(n != 0)
    {
        int d = n % 10;
   
        // if the digit is present
        // more than once in the
        // number
        if(s.find(d) != s.end())
        {
            // return 0 if the number
            // has repeated digit
            return 0;
        }
        s.insert(d);
        n = n / 10;
    }
    // return 1 if the number has
    // no repeated digit
    return 1;
}
   
// Function to find total number
// in the given range which has
// no repeated digit
int calculate(int L,int R)
{
    int answer = 0;
   
    // Traversing through the range
    for(int i = L; i < R + 1; ++i)
    {
   
        // Add 1 to the answer if i has
        // no repeated digit else 0
        answer = answer + repeated_digit(i);
    }
   
    return answer ;
}
   
// Driver Code
int main()
{
    int L = 1, R = 100;
   
    // Calling the calculate
    cout << calculate(L, R);
    return 0;
}
   
// This code is contributed by
// Sanjit_Prasad

                    

Java

// Java implementation of brute
// force solution.
import java.util.LinkedHashSet;
 
class GFG
{
// Function to check if the given
// number has repeated digit or not
static int repeated_digit(int n)
{
    LinkedHashSet<Integer> s = new LinkedHashSet<>();
 
    // Traversing through each digit
    while (n != 0)
    {
        int d = n % 10;
 
        // if the digit is present
        // more than once in the
        // number
        if (s.contains(d))
        {
            // return 0 if the number
            // has repeated digit
            return 0;
        }
        s.add(d);
        n = n / 10;
    }
     
    // return 1 if the number has
    // no repeated digit
    return 1;
}
 
// Function to find total number
// in the given range which has
// no repeated digit
static int calculate(int L, int R)
{
    int answer = 0;
 
    // Traversing through the range
    for (int i = L; i < R + 1; ++i)
    {
 
        // Add 1 to the answer if i has
        // no repeated digit else 0
        answer = answer + repeated_digit(i);
    }
 
    return answer;
}
 
// Driver Code
public static void main(String[] args)
{
    int L = 1, R = 100;
     
    // Calling the calculate
    System.out.println(calculate(L, R));
}
}
 
// This code is contributed by RAJPUT-JI

                    

Python3

# Python implementation of brute
# force solution.
 
# Function to check if the given
# number has repeated digit or not
def repeated_digit(n):
    a = []
     
    # Traversing through each digit
    while n != 0:
        d = n%10
         
        # if the digit is present
        # more than once in the
        # number
        if d in a:
             
            # return 0 if the number
            # has repeated digit
            return 0
        a.append(d)
        n = n//10
     
    # return 1 if the number has no
    # repeated digit
    return 1
 
# Function to find total number
# in the given range which has
# no repeated digit
def calculate(L,R):
    answer = 0
     
    # Traversing through the range
    for i in range(L,R+1):
         
        # Add 1 to the answer if i has
        # no repeated digit else 0
        answer = answer + repeated_digit(i)
     
    # return answer
    return answer
     
# Driver's Code
L=1
R=100
 
# Calling the calculate
print(calculate(L, R))

                    

C#

// C# implementation of brute
// force solution.
using System;
using System.Collections.Generic;
 
class GFG
{
 
// Function to check if the given
// number has repeated digit or not
static int repeated_digit(int n)
{
    var s = new HashSet<int>();
 
    // Traversing through each digit
    while (n != 0)
    {
        int d = n % 10;
 
        // if the digit is present
        // more than once in the
        // number
        if (s.Contains(d))
        {
            // return 0 if the number
            // has repeated digit
            return 0;
        }
        s.Add(d);
        n = n / 10;
    }
     
    // return 1 if the number has
    // no repeated digit
    return 1;
}
 
// Function to find total number
// in the given range which has
// no repeated digit
static int calculate(int L, int R)
{
    int answer = 0;
 
    // Traversing through the range
    for (int i = L; i < R + 1; ++i)
    {
 
        // Add 1 to the answer if i has
        // no repeated digit else 0
        answer = answer + repeated_digit(i);
    }
 
    return answer;
}
 
// Driver Code
public static void Main(String[] args)
{
    int L = 1, R = 100;
     
    // Calling the calculate
    Console.WriteLine(calculate(L, R));
}
}
 
// This code is contributed by RAJPUT-JI

                    

PHP

<?php
// PHP implementation of
// brute force solution.
 
// Function to check if
// the given number has
// repeated digit or not
function repeated_digit($n)
{
    $c = 10;
    $a = array_fill(0, $c, 0);
     
    // Traversing through
    // each digit
    while($n > 0)
    {
        $d = $n % 10;
         
        // if the digit is present
        // more than once in the
        // number
        if ($a[$d] > 0)
        {
            // return 0 if the number
            // has repeated digit
            return 0;
        }
        $a[$d]++;
        $n = (int)($n / 10);
    }
     
    // return 1 if the number
    // has no repeated digit
    return 1;
}
 
// Function to find total
// number in the given range
// which has no repeated digit
function calculate($L, $R)
{
    $answer = 0;
     
    // Traversing through
    // the range
    for($i = $L; $i <= $R; $i++)
    {
         
        // Add 1 to the answer if
        // i has no repeated digit
        // else 0
        $answer += repeated_digit($i);
    }
     
    // return answer
    return $answer;
}
 
// Driver Code
$L = 1;
$R = 100;
 
// Calling the calculate
echo calculate($L, $R);
 
// This code is contributed by mits
?>

                    

Javascript

// JS implementation of brute
// force solution.
 
// Function to check if the given
// number has repeated digit or not
function repeated_digit(n)
{
    let s = new Set();
 
    // Traversing through each digit
    while(n != 0)
    {
        let d = n % 10;
 
        // if the digit is present
        // more than once in the
        // number
        if(s.has(d))
        {
            // return 0 if the number
            // has repeated digit
            return 0;
        }
        s.add(d);
        n = Math.floor(n / 10);
    }
    // return 1 if the number has
    // no repeated digit
    return 1;
}
 
// Function to find total number
// in the given range which has
// no repeated digit
function calculate(L, R)
{
    let answer = 0;
 
    // Traversing through the range
    for(var i = L; i < R + 1; ++i)
    {
 
        // Add 1 to the answer if i has
        // no repeated digit else 0
        answer = answer + repeated_digit(i);
    }
 
    return answer ;
}
 
// Driver Code
let  L = 1, R = 100;
 
// Calling the calculate
console.log(calculate(L, R))
 
 
// This code is contributed by
// phasing17

                    

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. Prefix[i]                    = Total number with no repeated digit less than or equal to 1. Therefore each query can be solved in O(1) time. Answer = Prefix[R] - Prefix[L-1]

Below is the implementation of above idea.

C++

// C++ implementation of above idea
#include <bits/stdc++.h>
 
using namespace std;
 
// Maximum
int MAX = 1000;
 
// Prefix Array
vector<int> Prefix = {0};
 
// Function to check if the given
// number has repeated digit or not
int repeated_digit(int n)
{
     
    unordered_set<int> a;
    int d;
     
    // Traversing through each digit
    while (n != 0)
    {
        d = n % 10;
         
        // if the digit is present
        // more than once in the
        // number
        if (a.find(d) != a.end())
             
            // return 0 if the number
            // has repeated digit
            return 0;
         
        a.insert(d);
        n = n / 10;
    }
     
    // return 1 if the number has no
    // repeated digit
    return 1;
}
 
// Function to pre calculate
// the Prefix array
void pre_calculation(int MAX)
{
     
    Prefix.push_back(repeated_digit(1));
     
    // Traversing through the numbers
    // from 2 to MAX
    for (int i = 2; i < MAX + 1; i++)
         
        // Generating the Prefix array
        Prefix.push_back(repeated_digit(i) + Prefix[i-1]);
}
 
// Calculate Function
int calculate(int L,int R)
{
     
    // Answer
    return Prefix[R] - Prefix[L-1];
}
 
// Driver code
int main()
{
    int L = 1, R = 100;
     
    // Pre-calculating the Prefix array.
    pre_calculation(MAX);
     
    // Calling the calculate function
    // to find the total number of number
    // which has no repeated digit
    cout << calculate(L, R) << endl;
 
    return 0;
}
 
// This code is contributed by Rituraj Jain

                    

Java

// Java implementation of above idea
import java.util.*;
 
class GFG
{
 
    // Maximum
    static int MAX = 100;
 
    // Prefix Array
    static Vector<Integer> Prefix = new Vector<>();
 
    // Function to check if the given
    // number has repeated digit or not
    static int repeated_digit(int n)
    {
        HashSet<Integer> a = new HashSet<>();
        int d;
 
        // Traversing through each digit
        while (n != 0)
        {
            d = n % 10;
 
            // if the digit is present
            // more than once in the
            // number
            if (a.contains(d))
 
                // return 0 if the number
                // has repeated digit
                return 0;
            a.add(d);
            n /= 10;
        }
 
        // return 1 if the number has no
        // repeated digit
        return 1;
    }
 
    // Function to pre calculate
    // the Prefix array
    static void pre_calculations()
    {
        Prefix.add(0);
        Prefix.add(repeated_digit(1));
 
        // Traversing through the numbers
        // from 2 to MAX
        for (int i = 2; i < MAX + 1; i++)
 
            // Generating the Prefix array
            Prefix.add(repeated_digit(i) + Prefix.elementAt(i - 1));
    }
 
    // Calculate Function
    static int calculate(int L, int R)
    {
 
        // Answer
        return Prefix.elementAt(R) - Prefix.elementAt(L - 1);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int L = 1, R = 100;
 
        // Pre-calculating the Prefix array.
        pre_calculations();
 
        // Calling the calculate function
        // to find the total number of number
        // which has no repeated digit
        System.out.println(calculate(L, R));
    }
}
 
// This code is contributed by
// sanjeev2552

                    

Python3

# Python implementation of
# above idea
 
# Prefix Array
Prefix = [0]
 
# Function to check if
# the given number has
# repeated digit or not
def repeated_digit(n):
    a = []
     
    # Traversing through each digit
    while n != 0:
        d = n%10
         
        # if the digit is present
        # more than once in the
        # number
        if d in a:
             
            # return 0 if the number
            # has repeated digit
            return 0
        a.append(d)
        n = n//10
     
    # return 1 if the number has no
    # repeated digit
    return 1
 
# Function to pre calculate
# the Prefix array
def pre_calculation(MAX):
     
    # To use to global Prefix array
    global Prefix
    Prefix.append(repeated_digit(1))
     
    # Traversing through the numbers
    # from 2 to MAX
    for i in range(2,MAX+1):
         
        # Generating the Prefix array
        Prefix.append( repeated_digit(i) +
                       Prefix[i-1] )
 
# Calculate Function
def calculate(L,R):
     
    # Answer
    return Prefix[R]-Prefix[L-1]
 
 
# Driver Code
 
# Maximum
MAX = 1000
 
# Pre-calculating the Prefix array.
pre_calculation(MAX)
 
# Range
L=1
R=100
 
# Calling the calculate function
# to find the total number of number
# which has no repeated digit
print(calculate(L, R))

                    

C#

// C# implementation of above idea
using System;
using System.Collections.Generic;
 
class GFG
{
 
    // Maximum
    static int MAX = 100;
 
    // Prefix Array
    static List<int> Prefix = new List<int>();
 
    // Function to check if the given
    // number has repeated digit or not
    static int repeated_digit(int n)
    {
        HashSet<int> a = new HashSet<int>();
        int d;
 
        // Traversing through each digit
        while (n != 0)
        {
            d = n % 10;
 
            // if the digit is present
            // more than once in the
            // number
            if (a.Contains(d))
 
                // return 0 if the number
                // has repeated digit
                return 0;
            a.Add(d);
            n /= 10;
        }
 
        // return 1 if the number has no
        // repeated digit
        return 1;
    }
 
    // Function to pre calculate
    // the Prefix array
    static void pre_calculations()
    {
        Prefix.Add(0);
        Prefix.Add(repeated_digit(1));
 
        // Traversing through the numbers
        // from 2 to MAX
        for (int i = 2; i < MAX + 1; i++)
 
            // Generating the Prefix array
            Prefix.Add(repeated_digit(i) +
                           Prefix[i - 1]);
    }
 
    // Calculate Function
    static int calculate(int L, int R)
    {
 
        // Answer
        return Prefix[R] - Prefix[L - 1];
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int L = 1, R = 100;
 
        // Pre-calculating the Prefix array.
        pre_calculations();
 
        // Calling the calculate function
        // to find the total number of number
        // which has no repeated digit
        Console.WriteLine(calculate(L, R));
    }
}
 
// This code is contributed by 29AjayKumar

                    

JavaScript

<script>
    // JavaScript implementation of brute
// force solution.
 
// Function to check if the given
// number has repeated digit or not
function repeated_digit(n){
    const s = new Set();
 
    // Traversing through each digit
    while(n != 0){
        let d = n % 10;
 
        // if the digit is present
        // more than once in the
        // number
        if(s.has(d)){
            // return 0 if the number
            // has repeated digit
            return 0;
        }
        s.add(d);
        n = Math.floor(n / 10);
    }
    // return 1 if the number has
    // no repeated digit
    return 1;
}
 
// Function to find total number
// in the given range which has
// no repeated digit
function calculate(L, R){
    let answer = 0;
 
    // Traversing through the range
    for(let i = L; i < R + 1; ++i){
        // Add 1 to the answer if i has
        // no repeated digit else 0
        answer = answer + repeated_digit(i);
    }
 
    return answer ;
}
 
// Driver Code
{
    let L = 1, R = 100;
 
    // Calling the calculate
    console.log(calculate(L, R));
}
 
// This code is contributed by Gautam goel (gautamgoel962)
</script>

                    

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:

C++

// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
 
// DP table initialized with -1
int dp[11][2][(1LL << 10) - 1][2];
 
// Recursive Function to find numbers
// in the range L to R such that its
// digits are distinct
int recur(int i, int j, int k, int l, string a)
{
    // Base case
    if (i == a.size()) {
        return 1;
    }
 
    // If answer for current state is already
    // calculated then just return dp[i][j][k]
    if (dp[i][j][k][l] != -1)
        return dp[i][j][k][l];
 
    // Answer initialized with zero
    int ans = 0;
 
    // Tight condition true
    if (j == 1) {
 
        // Iterating from 0 to max value of
        // tight condition
        for (int digit = 0; digit <= 9; digit++) {
 
            // mask for digit
            int mask = (1 << digit);
 
            // if that digit is available to use
            if (mask & k) {
 
                // calling recursive function for max digit
                // taken and retaining tight condition
                if (digit == ((int)a[i] - 48)) {
                    ans += recur(i + 1, 1, k - (1 << digit),
                                 1, a);
                }
 
                // calling recursive function for zero
                // and dropping tight condition
                else if (digit == 0) {
                    ans += recur(i + 1, 0, k, 0, a);
                }
 
                // calling recursive function for number
                // less than max and dropping condition
                else if (digit < ((int)a[i] - 48)) {
                    ans += recur(i + 1, 0, k - (1 << digit),
                                 1, a);
                }
            }
        }
    }
 
    // Tight condition false
    else {
 
        // Iterating for all digits
        for (int digit = 0; digit <= 9; digit++) {
            int mask = (1 << digit);
 
            if (mask & k) {
                // calling recursive function for
                // not taking anything
                if (digit == 0 and l == 0)
                    ans += recur(i + 1, 0, k, 0, a);
 
                // calling recursive function for
                // taking zero
                else if (digit == 0 and l == 1)
                    ans += recur(i + 1, 0, k - (1 << digit),
                                 1, a);
 
                // calling recursive function for taking
                // digits from 1 to 9
                else
                    ans += recur(i + 1, 0, k - (1 << digit),
                                 1, a);
            }
        }
    }
 
    // Save and return dp value
    return dp[i][j][k][l] = ans;
}
 
// Function to find numbers
// in the range L to R such that its
// digits are distinct
int countInRange(int A, int B)
{
 
    // Initializing dp array with - 1
    memset(dp, -1, sizeof(dp));
 
    A--;
    string L = to_string(A), R = to_string(B);
 
    // Numbers with distinct digits in range 0 to L
    int ans1 = recur(0, 1, (1 << 10) - 1, 0, L);
 
    // Initializing dp array with - 1
    memset(dp, -1, sizeof(dp));
 
    // Numbers with distinct digits in range 0 to R
    int ans2 = recur(0, 1, (1 << 10) - 1, 0, R);
 
    // Difference of ans2 and ans1
    // will generate answer for required range
    return ans2 - ans1;
}
 
// Driver Code
int main()
{
    // Input 1
    int L = 1, R = 100;
 
    // Function Call
    cout << countInRange(L, R) << endl;
    return 0;
}

                    

Java

// Java code to implement the approach
import java.util.*;
 
class GFG {
 
  // DP table initialized with -1
  static int[][][][] dp = new int[11][2][(1 << 10)][2];
 
  // Recursive Function to find numbers
  // in the range L to R such that its
  // digits are distinct
  static int recur(int i, int j, int k, int l, String a)
  {
    // Base case
    if (i == a.length()) {
      return 1;
    }
 
    // If answer for current state is already
    // calculated then just return dp[i][j][k]
    if (dp[i][j][k][l] != -1)
      return dp[i][j][k][l];
 
    // Answer initialized with zero
    int ans = 0;
 
    // Tight condition true
    if (j == 1) {
      // Iterating from 0 to max value of
      // tight condition
      for (int digit = 0; digit <= 9; digit++) {
        // mask for digit
        int mask = (1 << digit);
 
        // if that digit is available to use
        if ((mask & k) != 0) {
 
          // calling recursive function for max
          // digit taken and retaining tight
          // condition
          if (digit == ((int)a.charAt(i) - 48)) {
            ans += recur(i + 1, 1,
                         k - (1 << digit), 1,
                         a);
          }
 
          // calling recursive function for zero
          // and dropping tight condition
          else if (digit == 0) {
            ans += recur(i + 1, 0, k, 0, a);
          }
 
          // calling recursive function for number
          // less than max and dropping condition
          else if (digit
                   < ((int)a.charAt(i) - 48)) {
            ans += recur(i + 1, 0,
                         k - (1 << digit), 1,
                         a);
          }
        }
      }
    }
    // Tight condition false
    else {
      // Iterating for all digits
      for (int digit = 0; digit <= 9; digit++) {
        int mask = (1 << digit);
 
        if ((mask & k) != 0) {
          // calling recursive function for
          // not taking anything
          if (digit == 0 && l == 0)
            ans += recur(i + 1, 0, k, 0, a);
 
          // calling recursive function for
          // taking zero
          else if (digit == 0 && l == 1)
            ans += recur(i + 1, 0,
                         k - (1 << digit), 1,
                         a);
 
          // calling recursive function for taking
          // digits from 1 to 9
          else
            ans += recur(i + 1, 0,
                         k - (1 << digit), 1,
                         a);
        }
      }
    }
 
    // Save and return dp value
    return dp[i][j][k][l] = ans;
  }
 
  // Function to find numbers
  // in the range L to R such that its
  // digits are distinct
  static int countInRange(int A, int B)
  {
 
    // Initializing dp array with - 1
    for (int[][][] table : dp) {
      for (int[][] row : table) {
        for (int[] innerRow : row) {
          Arrays.fill(innerRow, -1);
        }
      }
    }
 
    A--;
    String L = String.valueOf(A);
    String R = String.valueOf(B);
 
    // Numbers with distinct digits in range 0 to L
    int ans1 = recur(0, 1, (1 << 10) - 1, 0, L);
 
    // Initializing dp array with - 1
    for (int[][][] table : dp) {
      for (int[][] row : table) {
        for (int[] innerRow : row) {
          Arrays.fill(innerRow, -1);
        }
      }
    }
 
    // Numbers with distinct digits in range 0 to R
    int ans2 = recur(0, 1, (1 << 10) - 1, 0, R);
 
    // Difference of ans2 and ans1
    // will generate answer for required range
    return ans2 - ans1;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    // Input 1
    int L = 1, R = 100;
 
    // Function Call
    System.out.println(countInRange(L, R));
  }
}

                    

Python3

# Python code to implement the approach
# DP table initialized with -1
dp = [[[[-1 for l in range(2)] for k in range(1 << 10)] for j in range(2)] for i in range(11)]
 
def memset(dp):
    for i in range(11):
        for j in range(2):
            for k in range(1 << 10):
                for l in range(2):
                    dp[i][j][k][l] = -1
 
# Recursive Function to find numbers
# in the range L to R such that its
# digits are distinct
def recur(i, j, k, l, a):
    # Base case
    if i == len(a):
        return 1
     
    # If answer for current state is already
    # calculated then just return dp[i][j][k]
    if dp[i][j][k][l] != -1:
        return dp[i][j][k][l]
     
    # Answer initialized with zero
    ans = 0
     
    # Tight condition true
    if j == 1:
       
        # Iterating from 0 to max value of
        # tight condition
        for digit in range(10):
           
            # mask for digit
            mask = (1 << digit)
             
            # if that digit is available to use
            if mask & k:
               
                # calling recursive function for max digit
                # taken and retaining tight condition
                if digit == int(a[i]):
                    ans += recur(i + 1, 1, k - (1 << digit), 1, a)
                     
                # calling recursive function for zero
                # and dropping tight condition
                elif digit == 0:
                    ans += recur(i + 1, 0, k, 0, a)
                     
                # calling recursive function for number
                # less than max and dropping condition
                elif digit < int(a[i]):
                    ans += recur(i + 1, 0, k - (1 << digit), 1, a)
                     
    # Tight condition false
    else:
       
        # Iterating for all digits
        for digit in range(10):
            mask = (1 << digit)
            if mask & k:
               
                # calling recursive function for
                # not taking anything
                if digit == 0 and l == 0:
                    ans += recur(i + 1, 0, k, 0, a)
                     
                # calling recursive function for
                # taking zero
                elif digit == 0 and l == 1:
                    ans += recur(i + 1, 0, k - (1 << digit), 1, a)
                     
                # calling recursive function for taking
                # digits from 1 to 9
                else:
                    ans += recur(i + 1, 0, k - (1 << digit), 1, a)
 
    dp[i][j][k][l] = ans
     
    # Save and return dp value
    return ans
 
# Function to find numbers
# in the range L to R such that its
# digits are distinct
def countInRange(A, B):
   
    # Initializing dp array with - 1
    memset(dp)
    A -= 1
    L = str(A)
    R = str(B)
     
    # Numbers with distinct digits in range 0 to
    ans1 = recur(0, 1, (1 << 10) - 1, 0, L)
     
    # Initializing dp array with - 1
    memset(dp)
     
    # Numbers with distinct digits in range 0 to R
    ans2 = recur(0, 1, (1 << 10) - 1, 0, R)
     
    # Difference of ans2 and ans1
    # will generate answer for required range
    return ans2 - ans1
 
# Driver Code
 
# Input 1
L = 1
R = 100
 
# Function Call
print(countInRange(L, R))
 
# This code is contributed by prajwalkandekar123.

                    

C#

// C# code to implement the approach
using System;
public class GFG
{
    // DP table initialized with -1
    static int[,,,] dp = new int[11, 2, (1 << 10), 2];
 
    // Recursive Function to find numbers
    // in the range L to R such that its
    // digits are distinct
    static int recur(int i, int j, int k, int l, String a)
    {
        // Base case
        if (i == a.Length)
        {
            return 1;
        }
 
        // If answer for current state is already
        // calculated then just return dp[i][j][k]
        if (dp[i, j, k, l] != -1)
            return dp[i, j, k, l];
 
        // Answer initialized with zero
        int ans = 0;
 
        // Tight condition true
        if (j == 1)
        {
            // Iterating from 0 to max value of
            // tight condition
            for (int digit = 0; digit <= 9; digit++)
            {
                // mask for digit
                int mask = (1 << digit);
 
                // if that digit is available to use
                if ((mask & k) != 0)
                {
 
                    // calling recursive function for max
                    // digit taken and retaining tight
                    // condition
                    if (digit == ((int)a[i] - 48))
                    {
                        ans += recur(i + 1, 1,
                                     k - (1 << digit), 1,
                                     a);
                    }
 
                    // calling recursive function for zero
                    // and dropping tight condition
                    else if (digit == 0)
                    {
                        ans += recur(i + 1, 0, k, 0, a);
                    }
 
                    // calling recursive function for number
                    // less than max and dropping condition
                    else if (digit
                             < ((int)a[i] - 48))
                    {
                        ans += recur(i + 1, 0,
                                     k - (1 << digit), 1,
                                     a);
                    }
                }
            }
        }
        // Tight condition false
        else
        {
            // Iterating for all digits
            for (int digit = 0; digit <= 9; digit++)
            {
                int mask = (1 << digit);
 
                if ((mask & k) != 0)
                {
                    // calling recursive function for
                    // not taking anything
                    if (digit == 0 && l == 0)
                        ans += recur(i + 1, 0, k, 0, a);
 
                    // calling recursive function for
                    // taking zero
                    else if (digit == 0 && l == 1)
                        ans += recur(i + 1, 0,
                                     k - (1 << digit), 1,
                                     a);
 
                    // calling recursive function for taking
                    // digits from 1 to 9
                    else
                        ans += recur(i + 1, 0,
                                     k - (1 << digit), 1,
                                     a);
                }
            }
        }
 
        // Save and return dp value
        return dp[i, j, k, l] = ans;
    }
 
    // Function to find numbers
    // in the range L to R such that its
    // digits are distinct
    static int countInRange(int A, int B)
    {
 
        // Initializing dp array with - 1
        for (int i = 0; i < dp.GetLength(0); i++)
        {
            for (int j = 0; j < dp.GetLength(1); j++)
            {
                for (int k = 0; k < dp.GetLength(2); k++)
                {
                    for (int l = 0; l < dp.GetLength(3); l++)
                    {
                        dp[i, j, k, l] = -1;
                    }
                }
            }
        }
 
        A--;
        String L = A.ToString();
        String R = B.ToString();
 
        // Numbers with distinct digits in range 0 to L
        int ans1 = recur(0, 1, (1 << 10) - 1, 0, L);
 
        // Initializing dp array with - 1
        for (int i = 0; i < dp.GetLength(0); i++)
        {
            for (int j = 0; j < dp.GetLength(1); j++)
            {
                for (int k = 0; k < dp.GetLength(2); k++)
                {
                    for (int l = 0; l < dp.GetLength(3); l++)
                    {
                        dp[i, j, k, l] = -1;
                    }
                }
            }
        }
 
        // Numbers with distinct digits in range 0 to R
        int ans2 = recur(0, 1, (1 << 10) - 1, 0, R);
 
        // Difference of ans2 and ans1
        // will generate answer for required range
        return ans2 - ans1;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        // Input 1
        int L = 1, R = 100;
 
        // Function Call
        Console.WriteLine(countInRange(L, R));
    }
}

                    

Javascript

// Javascript code to implement the approach
 
// DP table initialized with -1
//int dp[11][2][(1LL << 10) - 1][2];
let dp=new Array(11);
for(let i=0; i<11; i++)
{
    dp[i]=new Array(2);
    for(let j=0; j<2; j++)
    {
        dp[i][j]=new Array(1<<10);
        for(let k=0; k<(1<<10); k++)
            dp[i][j][k]=new Array(2);
    }
}
 
function memset(dp)
{
    for(let i=0; i<11; i++)
    {
        for(let j=0; j<2; j++)
        {
            for(let k=0; k<(1<<10); k++)
                for(let l=0; l<2; l++)
                    dp[i][j][k][l]=-1;
        }
    }
}
 
// Recursive Function to find numbers
// in the range L to R such that its
// digits are distinct
function recur(i, j, k, l, a)
{
    // Base case
    if (i == a.length) {
        return 1;
    }
 
    // If answer for current state is already
    // calculated then just return dp[i][j][k]
    if (dp[i][j][k][l] != -1)
        return dp[i][j][k][l];
 
    // Answer initialized with zero
    let ans = 0;
 
    // Tight condition true
    if (j == 1) {
 
        // Iterating from 0 to max value of
        // tight condition
        for (let digit = 0; digit <= 9; digit++) {
 
            // mask for digit
            let mask = (1 << digit);
 
            // if that digit is available to use
            if (mask & k) {
 
                // calling recursive function for max digit
                // taken and retaining tight condition
                if (digit == (parseInt(a[i]))) {
                    ans += recur(i + 1, 1, k - (1 << digit),
                                 1, a);
                }
 
                // calling recursive function for zero
                // and dropping tight condition
                else if (digit == 0) {
                    ans += recur(i + 1, 0, k, 0, a);
                }
 
                // calling recursive function for number
                // less than max and dropping condition
                else if (digit < (parseInt(a[i]))) {
                    ans += recur(i + 1, 0, k - (1 << digit),
                                 1, a);
                }
            }
        }
    }
 
    // Tight condition false
    else {
 
        // Iterating for all digits
        for (let digit = 0; digit <= 9; digit++) {
            let mask = (1 << digit);
 
            if (mask & k) {
                // calling recursive function for
                // not taking anything
                if (digit == 0 && l == 0)
                    ans += recur(i + 1, 0, k, 0, a);
 
                // calling recursive function for
                // taking zero
                else if (digit == 0 && l == 1)
                    ans += recur(i + 1, 0, k - (1 << digit),
                                 1, a);
 
                // calling recursive function for taking
                // digits from 1 to 9
                else
                    ans += recur(i + 1, 0, k - (1 << digit),
                                 1, a);
            }
        }
    }
 
    // Save and return dp value
    return dp[i][j][k][l] = ans;
}
 
// Function to find numbers
// in the range L to R such that its
// digits are distinct
function countInRange(A, B)
{
 
    // Initializing dp array with - 1
    memset(dp);
 
    A--;
    let L = A.toString(), R = B.toString();
 
    // Numbers with distinct digits in range 0 to L
    let ans1 = recur(0, 1, (1 << 10) - 1, 0, L);
 
    // Initializing dp array with - 1
    memset(dp);
 
    // Numbers with distinct digits in range 0 to R
    let ans2 = recur(0, 1, (1 << 10) - 1, 0, R);
 
    // Difference of ans2 and ans1
    // will generate answer for required range
    return ans2 - ans1;
}
 
// Driver Code
    // Input 1
    let L = 1, R = 100;
 
    // Function Call
    console.log(countInRange(L, R));

                    

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:



Previous Article
Next Article

Similar Reads

Total count of sorted numbers upto N digits in range [L, R] (Magnificent necklace combinatorics problem)
Given three integers N, L, and R, the task is to print the total count of ways to form a necklace of at most N pearls such that the values of a pearl lie in the range [L, R] and are in ascending order. Examples: Input: N = 3, L = 6, R = 9Output: 34Explanation:The necklace can be formed in the following ways: The necklaces of length one that can be
8 min read
Numbers of Length N having digits A and B and whose sum of digits contain only digits A and B
Given three positive integers N, A, and B. The task is to count the numbers of length N containing only digits A and B and whose sum of digits also contains the digits A and B only. Print the answer modulo 109 + 7.Examples: Input: N = 3, A = 1, B = 3 Output: 1 Possible numbers of length 3 are 113, 131, 111, 333, 311, 331 and so on... But only 111 i
15 min read
Count of numbers between range having only non-zero digits whose sum of digits is N and number is divisible by M
Given a range [L, R] and two positive integers N and M. The task is to count the numbers in the range containing only non-zero digits whose sum of digits is equal to N and the number is divisible by M.Examples: Input: L = 1, R = 100, N = 8, M = 2 Output: 4 Only 8, 26, 44 and 62 are valid numbers Input: L = 1, R = 200, N = 4, M = 11 Output: 2 Only 2
14 min read
Count numbers in given range such that sum of even digits is greater than sum of odd digits
Given two integers L and R denoting a range [L, R]. The task is to find the total count of numbers in the given range [L,R] whose sum of even digits is greater than the sum of odd digits. Examples: Input : L=2 R=10 Output : 4 Numbers having the property that sum of even digits is greater than sum of odd digits are: 2, 4, 6, 8 Input : L=2 R=17 Outpu
14 min read
Count numbers from given range having odd digits at odd places and even digits at even places
Given two integers L and R, the task is to count numbers from the range [L, R] having odd digits at odd positions and even digits at even positions respectively. Examples: Input: L = 3, R = 25Output: 9Explanation: The numbers satisfying the conditions are 3, 5, 7, 9, 10, 12, 14, 16 and 18. Input: L = 128, R = 162Output: 7Explanation: The numbers sa
15+ min read
Count numbers from a given range that can be expressed as sum of digits raised to the power of count of digits
Given an array arr[] consisting of queries of the form {L, R}, the task for each query is to count the numbers in the range [L, R] that can be expressed as the sum of its digits raised to the power of count of digits. Examples: Input: arr[][] = {{8, 11}}Output: 2Explanation:From the given range [1, 9], the numbers that can be expressed as the sum o
10 min read
Count of numbers in range [L, R] having sum of digits of its square equal to square of sum of digits
Given two integers L and R, the task is to find the count of numbers in range [L, R] such that the sum of digits of its square is equal to the square of sum of its digits, Example: Input: L = 22, R = 22Output: 1Explanation: 22 is only valid number in this range as sum of digits of its square = S(22*22) = S(484) = 16 and square of sum of its digits
11 min read
Count numbers in range whose sum of digits is divisible by XOR of digits
Given integers L and R, the task for this problem is to find a number of integers in the range L to R whose sum of digits is divisible by bitwise XOR of digits. print the answer. ( L <= R <= 1018) Note: Bitwise XOR sum zero never divides any other number. Examples: Input: L = 10, R = 15Output: 4Explanation: Number 10 : digitSum = 1 + 0 = 1, x
15+ min read
Squares of numbers with repeated single digits | Set 1 (3, 6 and 9)
Given a number made of single digits, find its square. It may be assumed that the single digits are 3, 6 and 9. Numbers can be very large i.e. can exceed long long int.Examples: Input : 33 66 99 Output : Square of 33 is : 1089 Square of 66 is : 4356 Square of 99 is : 9801 Input : 333 666 999 Output : Square of 333 is : 110889 Square of 666 is : 443
10 min read
Find the total count of numbers up to N digits in a given base B
Given two integers N and B, the task is to find the count of natural numbers of Base B up to N digits. Examples: Input: N = 2, B = 10 Output: 99 Explanation: 1, 2, 3, 4, 5, 6, 7, 8, 9 are 1 digit Natural numbers of Base 10. 10, 11, 12.........99 are 2 digit Natural numbers of Base 10 So, total = 9 + 90 = 99 Input: N = 2, B = 16 Output: 255 Explanat
4 min read
Count total number of N digit numbers such that the difference between sum of even and odd digits is 1
Given a number n, we need to count the total number of n digit numbers such that the sum of even digits is 1 more than the sum of odd digits. Here even and odd means positions of digits are like array indexes, for example, the leftmost (or leading) digit is considered as even digit, next to leftmost is considered as odd, and so on. Example: Input:
10 min read
Total number of non-decreasing numbers with n digits
A number is non-decreasing if every digit (except the first one) is greater than or equal to the previous digit. For example, 223, 4455567, 899, are non-decreasing numbers.So, given the number of digits n, you are required to find the count of total non-decreasing numbers with n digits. Examples: Input: n = 1Output: count = 10Input: n = 2Output: co
11 min read
Total ways of choosing X men and Y women from a total of M men and W women
Given four integers X, Y, M, and W. The task is to find the number of ways to choose X men and Y women from total M men and W women. Examples: Input: X = 1, Y = 2, M = 1, W = 3 Output: 3 Way 1: Choose the only man and 1st and 2nd women. Way 2: Choose the only man and 2nd and 3rd women. Way 3: Choose the only man and 1st and 3rd women. Input: X = 4,
9 min read
Minimum digits to be removed to make either all digits or alternating digits same
Given a numeric string str, the task is to find the minimum number of digits to be removed from the string such that it satisfies either of the below conditions: All the elements of the string are the same.All the elements at even position are same and all the elements at the odd position are same, which means the string is alternating with the equ
7 min read
Count total set bits in all numbers from range L to R
Given two positive integers L and R, the task is to count the total number of set bits in the binary representation of all the numbers from L to R. Examples: Input: L = 3, R = 5 Output: 5 Explanation: (3)10 = (11)2, (4)10 = (100)2, (5)10 = (101)2 So, Total set bit in range 3 to 5 is 5 Input: L = 10, R = 15 Output: 17 Method 1 - Naive Approach: The
15+ min read
Find K missing numbers from given Array in range [1, M] such that total average is X
Given an array arr[] of integers of size N where each element can be in the range [1, M], and two integers X and K. The task is to find K possible numbers in range [1, M] such that the average of all the (N + K) numbers is equal to X. If there are multiple valid answers, any one is acceptable. Examples: Input: arr[] = {3, 2, 4, 3}, M = 6, K = 2, X
6 min read
Count of integers in a range which have even number of odd digits and odd number of even digits
Given a range [L, R], the task is to count the numbers which have even number of odd digits and odd number of even digits. For example, 8 has 1 even digit and 0 odd digit - Satisfies the condition since 1 is odd and 0 is even.545 has 1 even digit and 2 odd digits - Satisfies the condition since 1 is odd and 2 is even.4834 has 3 even digits and 1 od
11 min read
Count number of integers in given range with adjacent digits different and sum of digits equal to M
Given integers T, A, and B, the task for this problem is to find numbers in the range [A, B] such that the adjacent digits of the number are different and the sum of digits is equal to T. ( A ? B ? 1018) Examples: Input: T = 5, A = 1, B = 100Output: 6Explanation: 5, 14, 23, 32, 41, and 50 are valid integers that are in between the range 1 to 100 an
15+ min read
Number of ways to obtain each numbers in range [1, b+c] by adding any two numbers in range [a, b] and [b, c]
Given three integers a, b and c. You need to select one integer from the range [a, b] and one integer from the range [b, c] and add them. The task to calculate the number of ways to obtain the sum for all the numbers in the range [1, b+c]. Examples: Input: a = 1, b = 2, c = 2 Output: 0, 0, 1, 1 Explanation: The numbers to be obtained are [1, b+c] =
10 min read
Remove repeated digits in a given number
Given an integer, remove consecutive repeated digits from it. Examples: Input: x = 12224 Output: 124 Input: x = 124422 Output: 1242 Input: x = 11332 Output: 132 We need to process all digits of n and remove consecutive representations. We can go through all digits by repeatedly dividing n with 10 and taking n%10. C/C++ Code // C++ program to remove
5 min read
Recursive sum of digits of a number formed by repeated appends
Given two positive number N and X. The task is to find the sum of digits of a number formed by N repeating X number of times until sum become single digit. Examples : Input : N = 24, X = 3 Output : 9 Number formed after repeating 24 three time = 242424 Sum = 2 + 4 + 2 + 4 + 2 + 4 = 18 Sum is not the single digit, so finding the sum of digits of 18,
5 min read
Find M-th number whose repeated sum of digits of a number is N
Given two positive integers N and M, The task is to find the M-th number whose sum of digits of a number until the sum becomes a single digit is N. Examples: Input: N = 1, M = 3Output: 19 The first two numbers are 1 and 10. Input: N = 2, M = 5Output: 38 The first four numbers are 2, 11, 20, and 29. A naive approach is to iterate for all numbers and
8 min read
Count ways to spell a number with repeated digits
Given a string that contains digits of a number. The number may contain many same continuous digits in it. The task is to count number of ways to spell the number. For example, consider 8884441100, one can spell it simply as triple eight triple four double two and double zero. One can also spell as double eight, eight, four, double four, two, two,
6 min read
Count total set bits in first N Natural Numbers (all numbers from 1 to N)
Given a positive integer N, the task is to count the total number of set bits in binary representation of all natural numbers from 1 to N. Examples: Input: N = 3Output: 4Explanation: Numbers from 1 to 3: {1, 2, 3}Binary Representation of 1: 01 -> Set bits = 1Binary Representation of 2: 10 -> Set bits = 1Binary Representation of 3: 11 -> Se
15+ min read
Smallest element repeated exactly ‘k’ times (not limited to small range)
Given an array of size n, the goal is to find out the smallest number that is repeated exactly ‘k’ times where k > 0? And Examples: Input : a[] = {2, 1, 3, 1, 2, 2} k = 3 Output : 2 Input : a[] = {3, 4, 3, 2, 1, 5, 5} k = 2 Output : 3 Explanation: As 3 is smaller than 5. So 3 should be printed.Recommended PracticeSmallest number repeating K time
5 min read
Count N-digit numbers whose digits does not exceed absolute difference of the two previous digits
Given an integer N, the task is to count the number of N-digit numbers such that each digit, except the first and second digits, is less than or equal to the absolute difference of the previous two digits. Examples: Input: N = 1Output: 10Explanation: All the numbers from [0 - 9] are valid because the number of digits is 1. Input : N = 3Output : 375
9 min read
Numbers with sum of digits equal to the sum of digits of its all prime factor
Given a range, the task is to find the count of the numbers in the given range such that the sum of its digit is equal to the sum of all its prime factors digits sum.Examples: Input: l = 2, r = 10 Output: 5 2, 3, 4, 5 and 7 are such numbers Input: l = 15, r = 22 Output: 3 17, 19 and 22 are such numbers As, 17 and 19 are already prime. Prime Factors
13 min read
Count of numbers upto N digits formed using digits 0 to K-1 without any adjacent 0s
Given two integers N and K, the task is to count the numbers up to N digits such that no two zeros are adjacents and the range of digits are from 0 to K-1.Examples: Input: N = 2, K = 3 Output: 8 Explanation: There are 8 such numbers such that digits are from 0 to 2 only, without any adjacent 0s: {1, 2, 10, 11, 12, 20, 21, 22}Input: N = 3, K = 3 Out
12 min read
Find two numbers A and B of X and Y digits respectively with GCD having Z digits
Given three positive integers X, Y, and Z. The task is to find two numbers A and B of X and Y digits respectively with their GCD having Z digits. where Z ≤ min(X, Y). If there are multiple possible answers print any of them. Examples: Input: X = 2, Y = 3, Z = 1Output: A = 11, B = 100 Explanation: A and B contains 2 and 3 digits respectively and GCD
5 min read
Count N-digits numbers made up of even and prime digits at odd and even positions respectively
Given a positive integer N, the task is to find the number of integers of N digits having even digits at odd indices and prime digits at even indices. Examples: Input: N = 2Output: 20Explanation:Following are the possible number of 2-digits satisfying the given criteria {20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 50, 52, 54, 56, 58, 70, 72, 74, 76, 78
12 min read