Count of integers in range [L, R] having even frequency of each digit

Given two integers L and R, the task is to find the count of integers in the range [L, R] such that the frequency of each digit in the integer is even.
Examples:
Input: L = 47, R = 999
Output: 5
Explanation: The integers that are in range [47, 999] and follow the given condition are {55, 66, 77, 88, 99}.Input: L = 32, R = 1010
Output: 9
Explanation: The integers that are in range [32, 1010] and follow the given condition are {33, 44, 55, 66, 77, 88, 99, 1001, 1010}.
Approach: The above problem can be solved with the help of Bitmasking and Dynamic Programming. Below are some observations that can be used to solve the given problem:
- Bitmask having 10 bits can be used to store the parity of each digit in the range [0, 9] where an ith set bit will represent the frequency of digit i in the integer as odd.
- Let’s define a function countInt(X) to find the count of valid integers in the range [1, X]. Therefore, the answer for range [L, R] can be calculated as countInt(R) – countInt(L-1).
Consider a 4D array say dp[][][][], wherein dp[mask][length][smaller][started], where mask represents the Bitmask denoting the parity of each digit from 0 to 9, length represents the total count of digits in the current number, smaller represents whether the current number is smaller than the upper bound i.e, lies in the given range and started will keep track of repeating numbers due to the leading zeroes. Below are the steps to follow:
- Create a recursive function to iterate through each index of the integer and recursively call the function for each valid digit at the current index of the integer.
- Keep track of the leading zeroes in the variable started in order to prevent their repetition in the count.
- If the current index is the most significant index, the valid digits must be in the range [1, 9] otherwise they can be in the range [0, 9].
- The current digit is a valid digit if after putting the digit in the current index of the integer, formed integer <= Upper Bound of the range.
- Memorize the count for each state and return the memorized value if the current state is already calculated.
Below is the implementation of the above approach:
C++
// C++ program for the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Stores the upper limit of the rangestring s;Â
// Stores the overlapping statesint dp[1024][10][2][2];Â
// Recursive Function to calculate the// count of valid integers in the range// [1, s] using memoizationint calcCnt(int mask, int len,            int smaller, int started){    // Base Case    if (len == s.size()) {Â
        // If current integer has even        // count of digits and is not        // repeated        return (mask == 0 && started);    }Â
    // If current state is already    // considered    if (dp[mask][len][smaller][started] != -1)        return dp[mask][len][smaller][started];Â
    // Stores the maximum valid digit at    // the current index    int mx = 9;    if (!smaller) {        mx = s[len] - '0';    }Â
    // Stores the count of valid integers    int ans = 0;Â
    // If the current digit is not the    // most significant digit, i.e, the    // integer is already started    if (started) {Â
        // Iterate through all valid digits        for (int i = 0; i <= mx; i++) {Â
            // Recursive call for ith digit            // at the current index            ans += calcCnt(mask ^ (1 << i), len + 1,                           smaller || (i < s[len] - '0'), 1);        }    }    else {Â
        // Recursive call for integers having        // leading zeroes in the beginning        ans = calcCnt(mask, len + 1, 1, 0);Â
        // Iterate through all valid digits as        // most significant digits        for (int i = 1; i <= mx; i++) {Â
            // Recursive call for ith digit            // at the current index            ans += calcCnt(mask ^ (1 << i), len + 1,                           smaller || (i < s[len] - '0'), 1);        }    }Â
    // Return answer    return dp[mask][len][smaller][started] = ans;}Â
// Function to calculate valid number in// the range [1, X]int countInt(int x){Â Â Â Â // Initialize dp array with -1Â Â Â Â memset(dp, -1, sizeof(dp));Â
    // Store the range in form of string    s = to_string(x);Â
    // Return Count    return calcCnt(0, 0, 0, 0);}Â
// Function to find the count of integers// in the range [L, R] such that the// frequency of each digit is evenint countIntInRange(int L, int R){Â Â Â Â return countInt(R) - countInt(L - 1);}Â
// Driver Codeint main(){Â Â Â Â int L = 32, R = 1010;Â Â Â Â cout << countIntInRange(L, R);Â
    return 0;} |
Java
// Java program for the above approachimport java.util.*;class GFG{Â
// Stores the upper limit of the rangestatic String s;Â
// Stores the overlapping statesstatic int [][][][] dp = new int[1024][10][2][2];Â
// Function to convert Integer to booleanstatic boolean toBoolean(int smaller){    if (smaller >= 1)        return true;    else       return false; }Â
// Recursive Function to calculate the// count of valid integers in the range// [1, s] using memoizationstatic int calcCnt(int mask, int len,            int smaller, int started){    // Base Case    if (len == s.length()) {Â
        // If current integer has even        // count of digits and is not        // repeated        if (mask == 0 && started !=0)          return 1;        else          return 0;         }Â
    // If current state is already    // considered    if (dp[mask][len][smaller][started] != -1)        return dp[mask][len][smaller][started];Â
    // Stores the maximum valid digit at    // the current index    int mx = 9;    if (smaller == 0) {        mx = (int)s.charAt(len) - 48;    }Â
    // Stores the count of valid integers    int ans = 0;Â
    // If the current digit is not the    // most significant digit, i.e, the    // integer is already started    if (started !=0) {Â
        // Iterate through all valid digits        for (int i = 0; i <= mx; i++) {Â
            // Recursive call for ith digit            // at the current index            ans += calcCnt(mask ^ (1 << i), len + 1,                           toBoolean(smaller) || (i < (int)s.charAt(len) - 48)?1:0,                           1);        }    }    else {Â
        // Recursive call for integers having        // leading zeroes in the beginning        ans = calcCnt(mask, len + 1, 1, 0);Â
        // Iterate through all valid digits as        // most significant digits        for (int i = 1; i <= mx; i++) {Â
            // Recursive call for ith digit            // at the current index            ans += calcCnt(mask ^ (1 << i), len + 1,                           toBoolean(smaller) || (i < (int)s.charAt(len) - 48)?1:0,                           1);        }    }Â
    // Return answer    dp[mask][len][smaller][started] = ans;    return ans;}Â
// Function to calculate valid number in// the range [1, X]static int countInt(int x){Â Â Â Â // Initialize dp array with -1Â Â Â Â for(int i = 0; i < 1024; i++){Â Â Â Â Â Â for(int j = 0; j < 10; j++){Â Â Â Â Â Â Â Â for(int k = 0; k < 2; k++){Â Â Â Â Â Â Â Â Â Â for(int l = 0; l < 2; l++)Â Â Â Â Â Â Â Â Â Â Â Â dp[i][j][k][l] = -1;Â Â Â Â Â Â Â Â }Â Â Â Â Â Â }Â Â Â Â }Â
    // Store the range in form of string    s = Integer.toString(x);Â
    // Return Count    return calcCnt(0, 0, 0, 0);}Â
// Function to find the count of integers// in the range [L, R] such that the// frequency of each digit is evenstatic int countIntInRange(int L, int R){Â Â Â Â return countInt(R) - countInt(L - 1);}Â
// Driver Codepublic static void main(String [] args){Â Â Â Â int L = 32, R = 1010;Â Â Â Â System.out.println(countIntInRange(L, R));}}Â
// This code is contributed by ihritik |
Python3
# Python program for the above approachÂ
# Stores the upper limit of the ranges = ""Â
# Stores the overlapping statesdp = [[[[0 for _ in range(2)] for _ in range(2)]Â Â Â Â Â Â Â for _ in range(10)] for _ in range(1024)]Â
# Recursive Function to calculate the# count of valid integers in the range#Â [1, s] using memoizationdef calcCnt(mask, sz, smaller, started):Â
    # Base Case    if (sz == len(s)):Â
        # If current integer has even        # count of digits and is not        # repeated        return (mask == 0 and started)Â
    # If current state is already    # considered    if (dp[mask][sz][smaller][started] != -1):        return dp[mask][sz][smaller][started]Â
    # Stores the maximum valid digit at    # the current index    mx = 9    if (not smaller):        mx = ord(s[sz]) - ord('0')Â
    # Stores the count of valid integers    ans = 0Â
    # If the current digit is not the    # most significant digit, i.e, the    # integer is already started    if (started):Â
        # Iterate through all valid digits        for i in range(0, mx+1):Â
            # Recursive call for ith digit            # at the current index            ans += calcCnt(mask ^ (1 << i), sz + 1,                           smaller or (i < ord(s[sz]) - ord('0')), 1)    else:Â
        # Recursive call for integers having        # leading zeroes in the beginning        ans = calcCnt(mask, sz + 1, 1, 0)Â
        # Iterate through all valid digits as        # most significant digits        for i in range(1, mx+1):Â
            # Recursive call for ith digit            # at the current index            ans += calcCnt(mask ^ (1 << i), sz + 1,                           smaller or (i < ord(s[sz]) - ord('0')), 1)    # Return answer    dp[mask][sz][smaller][started] = ans    return dp[mask][sz][smaller][started]Â
# Function to calculate valid number in# the range [1, X]def countInt(x):Â
    # Initialize dp array with -1    global dp    dp = [[[[-1 for _ in range(2)] for _ in range(2)]           for _ in range(10)] for _ in range(1024)]         # Store the range in form of string    global s    s = str(x)Â
    # Return Count    return calcCnt(0, 0, 0, 0)Â
# Function to find the count of integers# in the range [L, R] such that the# frequency of each digit is evendef countIntInRange(L, R):Â Â Â Â return countInt(R) - countInt(L - 1)Â
# Driver Codeif __name__ == "__main__":Â Â Â Â L = 32Â Â Â Â R = 1010Â Â Â Â print(countIntInRange(L, R))Â
    # This code is contributed by rakeshsahni |
C#
// C# program for the above approachusing System;using System.Collections.Generic;Â
class GFG{Â
// Stores the upper limit of the rangestatic string s;Â
// Stores the overlapping statesstatic int [,,,]dp = new int[1024, 10, 2, 2];Â
// Recursive Function to calculate the// count of valid integers in the range// [1, s] using memoizationstatic int calcCnt(int mask, int len,            int smaller, int started){    // Base Case    if (len == s.Length) {Â
        // If current integer has even        // count of digits and is not        // repeated        if (mask == 0 && started !=0)          return 1;        else          return 0;         }Â
    // If current state is already    // considered    if (dp[mask, len, smaller, started] != -1)        return dp[mask, len, smaller, started];Â
    // Stores the maximum valid digit at    // the current index    int mx = 9;    if (smaller == 0) {        mx = (int)s[len] - 48;    }Â
    // Stores the count of valid integers    int ans = 0;Â
    // If the current digit is not the    // most significant digit, i.e, the    // integer is already started    if (started !=0) {Â
        // Iterate through all valid digits        for (int i = 0; i <= mx; i++) {Â
            // Recursive call for ith digit            // at the current index            ans += calcCnt(mask ^ (1 << i), len + 1,                           Convert.ToBoolean(smaller) || (i < (int)s[len] - 48)?1:0,                           1);        }    }    else {Â
        // Recursive call for integers having        // leading zeroes in the beginning        ans = calcCnt(mask, len + 1, 1, 0);Â
        // Iterate through all valid digits as        // most significant digits        for (int i = 1; i <= mx; i++) {Â
            // Recursive call for ith digit            // at the current index            ans += calcCnt(mask ^ (1 << i), len + 1,                           Convert.ToBoolean(smaller) || (i < (int)s[len] - 48)?1:0,                           1);        }    }Â
    // Return answer    dp[mask, len, smaller, started] = ans;    return ans;}Â
// Function to calculate valid number in// the range [1, X]static int countInt(int x){Â Â Â Â // Initialize dp array with -1Â Â Â Â for(int i = 0; i < 1024; i++){Â Â Â Â Â Â for(int j = 0; j < 10; j++){Â Â Â Â Â Â Â Â for(int k = 0; k < 2; k++){Â Â Â Â Â Â Â Â Â Â for(int l = 0; l < 2; l++)Â Â Â Â Â Â Â Â Â Â Â Â dp[i, j, k, l] = -1;Â Â Â Â Â Â Â Â }Â Â Â Â Â Â }Â Â Â Â }Â
    // Store the range in form of string    s = x.ToString();Â
    // Return Count    return calcCnt(0, 0, 0, 0);}Â
// Function to find the count of integers// in the range [L, R] such that the// frequency of each digit is evenstatic int countIntInRange(int L, int R){Â Â Â Â return countInt(R) - countInt(L - 1);}Â
// Driver Codepublic static void Main(){Â Â Â Â int L = 32, R = 1010;Â Â Â Â Console.Write(countIntInRange(L, R));}}Â
// This code is contributed by ipg2016107. |
Javascript
// Javascript code to implement the approachÂ
// Stores the upper limit of the rangevar s = ""Â
// Stores the overlapping statesvar dp = new Array(1024)Â
// Function to convert Integer to booleanfunction toBoolean(smaller){    if (smaller >= 1){        return true    }    return false}Â
// Recursive Function to calculate the// count of valid integers in the range// [1, s] using memoizationfunction calcCnt(mask, len, smaller, started){    // Base Case    if (len == s.length) {Â
        // If current integer has even        // count of digits and is not        // repeated        if (mask == 0 && started !=0)            return 1;        else            return 0;         }Â
    // If current state is already    // considered    if (dp[mask][len][smaller][started] != -1)        return dp[mask][len][smaller][started]Â
    // Stores the maximum valid digit at    // the current index    var mx = 9    if (smaller == 0) {        mx = s.charCodeAt(len) - 48    }Â
    // Stores the count of valid integers    var ans = 0;Â
    // If the current digit is not the    // most significant digit, i.e, the    // integer is already started    if (started !=0) {Â
        // Iterate through all valid digits        for (let i = 0 ; i <= mx ; i++) {Â
            // Recursive call for ith digit            // at the current index            ans += calcCnt(mask ^ (1 << i), len + 1, toBoolean(smaller) || (i < s.charCodeAt(len) - 48) ? 1 : 0, 1)        }    }    else {Â
        // Recursive call for integers having        // leading zeroes in the beginning        ans = calcCnt(mask, len + 1, 1, 0)Â
        // Iterate through all valid digits as        // most significant digits        for (let i = 1 ; i <= mx ; i++) {Â
            // Recursive call for ith digit            // at the current index            ans += calcCnt(mask ^ (1 << i), len + 1, toBoolean(smaller) || (i < s.charCodeAt(len) - 48) ? 1 : 0, 1)        }    }Â
    // Return answer    dp[mask][len][smaller][started] = ans;    return ans;}Â
// Function to calculate valid number in// the range [1, X]function countInt(x){Â Â Â Â // Initialize dp array with -1Â Â Â Â for(let i = 0 ; i < 1024 ; i++){Â Â Â Â Â Â Â Â for(let j = 0 ; j < 10 ; j++){Â Â Â Â Â Â Â Â Â Â Â Â for(let k = 0 ; k < 2 ; k++){Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â for(let l = 0 ; l < 2 ; l++){Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â dp[i][j][k][l] = -1;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â }Â Â Â Â }Â
    // Store the range in form of string    s = x.toString()Â
    // Return Count    return calcCnt(0, 0, 0, 0)}Â
// Function to find the count of integers// in the range [L, R] such that the// frequency of each digit is evenfunction countIntInRange(L, R){Â Â Â Â return countInt(R) - countInt(L - 1);}Â
// Driver Codevar L = 32var R = 1010Â
for(let i = 0 ; i < 1024 ; i++){Â Â Â Â dp[i] = new Array(10)Â Â Â Â for(let j = 0 ; j < 10 ; j++){Â Â Â Â Â Â Â Â dp[i][j] = new Array(2)Â Â Â Â Â Â Â Â for(let k = 0 ; k < 2 ; k++){Â Â Â Â Â Â Â Â Â Â Â Â dp[i][j][k] = new Array(2)Â Â Â Â Â Â Â Â }Â Â Â Â }}Â
console.log(countIntInRange(L, R))Â
// This code is contributed by subhamgoyal2014. |
9
Â
Time Complexity:Â
Auxiliary Space:Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



