Related Articles

# Count of N-digit numbers with at least one digit repeating

• Difficulty Level : Medium
• Last Updated : 28 Jul, 2021

Given a positive integer N, the task is to find the number of N-digit numbers such that at least one digit in the number has occurred more than once.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

Input: N = 2
Output: 9
Explanation:
All the 2-digit number such that at least 1 digits occurs more than once are {11, 22, 33, 44, 55, 66, 77, 88, 99}. Therefore, the total count is 9.

Input: N = 5
Output: 62784

Naive Approach: The simplest approach to solve the given problem is to generate all possible N-digit numbers and count those numbers having at least one digit occurring more than once. After checking for all the numbers, print the value of the count as the resultant total count of numbers.

Time Complexity: O(N *10N)
Auxiliary Space: O(1)

Efficient Approach: The above approach can also be optimized by using Dynamic Programming because the above problem has Overlapping subproblems and an Optimal substructure. The subproblems can be stored in dp[][][] table memoization where dp[digit][mask][repeated] stores the answer from the digitth position till the end, where the mask stores all the digits included in the number till now and repeated denotes if any digit has occurred more than once. Follow the steps below to solve the problem:

• Initialize a global multidimensional array dp with all values as -1 that stores the result of each recursive call.
• Define a recursive function, say countOfNumbers(digit, mask, repeated, N) by performing the following steps.
• If the value of a digit is equal to (N + 1) then return 1 as a valid N-digit number is formed if repeated is equal to true. Otherwise, return 0.
• If repeated is equal to true, then return pow(10, N – digit + 1).
• If the current digit is 1, then any digit from [1, 9] can be placed and if N = 1, then 0 can be placed as well.
• Iterate over the range [N == 1 ? 0 : 1, 9] using the variable i and perform the following steps:
• If the ith bit of the mask is set, then add the value of countOfNumbers(digit + 1, mask|(1<<i), 1, N).
• Otherwise, add the value of countOfNumbers(digit + 1, mask|(1<<i), 0, N).
• Otherwise, iterate over the range [0, 9] using the variable i and perform the following steps:
• If the ith bit of the mask is set, then add the value of countOfNumbers(digit + 1, mask|(1<<i), 1, N).
• Otherwise, add the value of countOfNumbers(digit + 1, mask|(1<<i), 0, N).
• Return the sum of all possible valid placements of digits val as the result from the current recursive call.
• Print the value returned by the function countOfNumbers(1, 0, 0, N) as the resultant count of N-digit number satisfying the given criteria.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach``#include ``using` `namespace` `std;` `int` `dp[1 << 10];` `// Function to find the number of N``// digit numbers such that at least``// one digit occurs more than once``int` `countOfNumbers(``int` `digit, ``int` `mask,``                   ``bool` `repeated, ``int` `n)``{``    ``// Base Case``    ``if` `(digit == n + 1) {``        ``if` `(repeated == ``true``) {``            ``return` `1;``        ``}``        ``return` `0;``    ``}` `    ``// If repeated is true, then for``    ``// remaining positions any digit``    ``// can be placed``    ``if` `(repeated == ``true``) {``        ``return` `pow``(10, n - digit + 1);``    ``}` `    ``// If the current state has already``    ``// been computed, then return it``    ``int``& val = dp[digit][mask][repeated];``    ``if` `(val != -1) {``        ``return` `val;``    ``}` `    ``// Stores the count of number for``    ``// the current recursive calls``    ``val = 0;` `    ``// If current position is 1, then``    ``// any digit can be placed.` `    ``// If n = 1, 0 can be also placed``    ``if` `(digit == 1) {` `        ``for` `(``int` `i = (n == 1 ? 0 : 1);``             ``i <= 9; ++i) {` `            ``// If a digit has occurred``            ``// for the second time, then``            ``// set repeated to 1``            ``if` `(mask & (1 << i)) {``                ``val += countOfNumbers(``                    ``digit + 1, mask | (1 << i), 1, n);``            ``}` `            ``// Otherwise``            ``else` `{``                ``val += countOfNumbers(``                    ``digit + 1, mask | (1 << i), 0, n);``            ``}``        ``}``    ``}` `    ``// For remaining positions any``    ``// digit can be placed``    ``else` `{``        ``for` `(``int` `i = 0; i <= 9; ++i) {` `            ``// If a digit has occurred``            ``// for the second time, then``            ``// set repeated to 1``            ``if` `(mask & (1 << i)) {``                ``val += countOfNumbers(``                    ``digit + 1, mask | (1 << i), 1, n);``            ``}``            ``else` `{``                ``val += countOfNumbers(``                    ``digit + 1, mask | (1 << i), 0, n);``            ``}``        ``}``    ``}` `    ``// Return the resultant count for``    ``// the current recursive call``    ``return` `val;``}` `// Function to count all the N-digit``// numbers having at least one digit's``// occurrence more than once``void` `countNDigitNumber(``int` `N)``{``    ``// Initialize dp array with -1``    ``memset``(dp, -1, ``sizeof` `dp);` `    ``// Function to count all possible``    ``// number satisfying the given``    ``// criteria``    ``cout << countOfNumbers(1, 0, 0, N);``}` `// Driver Code``int` `main()``{``    ``int` `N = 2;``    ``countNDigitNumber(N);` `    ``return` `0;``}`

## Java

 `import` `java.util.Arrays;` `// Java program for the above approach` `class` `GFG {` `    ``public` `static` `int``[][][] dp = ``new` `int``[``50``][``1` `<< ``10``][``2``];` `    ``// Function to find the number of N``    ``// digit numbers such that at least``    ``// one digit occurs more than once``    ``public` `static` `int` `countOfNumbers(``int` `digit, ``int` `mask,``                                     ``int` `repeated, ``int` `n)``    ``{``      ` `        ``// Base Case``        ``if` `(digit == n + ``1``) {``            ``if` `(repeated == ``1``) {``                ``return` `1``;``            ``}``            ``return` `0``;``        ``}` `        ``// If repeated is true, then for``        ``// remaining positions any digit``        ``// can be placed``        ``if` `(repeated == ``1``) {``            ``return` `(``int``) Math.pow(``10``, n - digit + ``1``);``        ``}` `        ``// If the current state has already``        ``// been computed, then return it``        ``int` `val = dp[digit][mask][repeated];``        ``if` `(val != -``1``) {``            ``return` `val;``        ``}` `        ``// Stores the count of number for``        ``// the current recursive calls``        ``val = ``0``;` `        ``// If current position is 1, then``        ``// any digit can be placed.` `        ``// If n = 1, 0 can be also placed``        ``if` `(digit == ``1``) {` `            ``for` `(``int` `i = (n == ``1` `? ``0` `: ``1``); i <= ``9``; ++i) {` `                ``// If a digit has occurred``                ``// for the second time, then``                ``// set repeated to 1``                ``if` `((mask & (``1` `<< i)) > ``0``) {``                    ``val += countOfNumbers(digit + ``1``, mask | (``1` `<< i), ``1``, n);``                ``}` `                ``// Otherwise``                ``else` `{``                    ``val += countOfNumbers(digit + ``1``, mask | (``1` `<< i), ``0``, n);``                ``}``            ``}``        ``}` `        ``// For remaining positions any``        ``// digit can be placed``        ``else` `{``            ``for` `(``int` `i = ``0``; i <= ``9``; ++i) {` `                ``// If a digit has occurred``                ``// for the second time, then``                ``// set repeated to 1``                ``if` `((mask & (``1` `<< i)) > ``0``) {``                    ``val += countOfNumbers(digit + ``1``, mask | (``1` `<< i), ``1``, n);``                ``} ``else` `{``                    ``val += countOfNumbers(digit + ``1``, mask | (``1` `<< i), ``0``, n);``                ``}``            ``}``        ``}` `        ``// Return the resultant count for``        ``// the current recursive call``        ``return` `val;``    ``}` `    ``// Function to count all the N-digit``    ``// numbers having at least one digit's``    ``// occurrence more than once``    ``public` `static` `void` `countNDigitNumber(``int` `N)``    ``{``      ` `        ``// Initialize dp array with -1``        ``for` `(``int` `i = ``0``; i < ``50``; i++) {``            ``for` `(``int` `j = ``0``; j < ``1` `<< ``10``; j++) {``                ``for` `(``int` `k = ``0``; k < ``2``; k++) {``                    ``dp[i][j][k] = -``1``;``                ``}``            ``}``        ``}``      ` `        ``// Function to count all possible``        ``// number satisfying the given``        ``// criteria``        ``System.out.println(countOfNumbers(``1``, ``0``, ``0``, N));``    ``}` `    ``// Driver Code``    ``public` `static` `void` `main(String args[])``    ``{``        ``int` `N = ``2``;``        ``countNDigitNumber(N);` `    ``}``}` `// This code is contributed by gfgking.`

## Python3

 `# Python program for the above approach` `dp ``=` `[[[``-``1` `for` `i ``in` `range``(``2``)] ``for` `i ``in` `range``(``1` `<< ``10``)] ``for` `i ``in` `range``(``50``)]` `# Function to find the number of N``# digit numbers such that at least``# one digit occurs more than once``def` `countOfNumbers(digit, mask, repeated, n):``    ``global` `dp``    ``# Base Case``    ``if` `(digit ``=``=` `n ``+` `1``):``        ``if` `(repeated ``=``=` `True``):``            ``return` `1``        ``return` `0` `    ``# If repeated is true, then for``    ``# remaining positions any digit``    ``# can be placed``    ``if` `(repeated ``=``=` `True``):``        ``return` `pow``(``10``, n ``-` `digit ``+` `1``)` `    ``# If the current state has already``    ``# been computed, then return it``    ``val ``=` `dp[digit][mask][repeated]``    ``if` `(val !``=` `-``1``):``        ``return` `val` `    ``# Stores the count of number for``    ``# the current recursive calls``    ``val ``=` `4` `    ``# If current position is 1, then``    ``# any digit can be placed.` `    ``# If n = 1, 0 can be also placed``    ``if` `(digit ``=``=` `1``):` `        ``for` `i ``in` `range``((``0` `if` `(n``=``=``1``) ``else` `1``),``10``):``            ``# If a digit has occurred``            ``# for the second time, then``            ``# set repeated to 1``            ``if` `(mask & (``1` `<< i)):``                ``val ``+``=` `countOfNumbers(digit ``+` `1``, mask | (``1` `<< i), ``1``, n)``            ``# Otherwise``        ``else``:``                ``val ``+``=` `countOfNumbers(digit ``+` `1``, mask | (``1` `<< i), ``0``, n)` `    ``# For remaining positions any``    ``# digit can be placed``    ``else``:``        ``for` `i ``in` `range``(``10``):``            ``# If a digit has occurred``            ``# for the second time, then``            ``# set repeated to 1``            ``if` `(mask & (``1` `<< i)):``                ``val ``+``=` `countOfNumbers(digit ``+` `1``, mask | (``1` `<< i), ``1``, n)``        ``else``:``                ``val ``+``=` `countOfNumbers(digit ``+` `1``, mask | (``1` `<< i), ``0``, n)` `    ``# Return the resultant count for``    ``# the current recursive call``    ``dp[digit][mask][repeated] ``=` `val``    ``return` `dp[digit][mask][repeated]` `# Function to count all the N-digit``# numbers having at least one digit's``# occurrence more than once``def` `countNDigitNumber(N):` `    ``# Function to count all possible``    ``# number satisfying the given``    ``# criteria``    ``print`  `(countOfNumbers(``1``, ``0``, ``0``, N))` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ``N ``=` `2``    ``countNDigitNumber(N)` `# This code is contributed by mohit kumar 29.`

## C#

 `// C# program for the above approach``using` `System;` `class` `GFG{` `public` `static` `int``[,,] dp = ``new` `int``[50, 1 << 10, 2];` `// Function to find the number of N``// digit numbers such that at least``// one digit occurs more than once``public` `static` `int` `countOfNumbers(``int` `digit, ``int` `mask,``                                 ``int` `repeated, ``int` `n)``{``    ` `    ``// Base Case``    ``if` `(digit == n + 1)``    ``{``        ``if` `(repeated == 1)``        ``{``            ``return` `1;``        ``}``        ``return` `0;``    ``}` `    ``// If repeated is true, then for``    ``// remaining positions any digit``    ``// can be placed``    ``if` `(repeated == 1)``    ``{``        ``return``(``int``)Math.Pow(10, n - digit + 1);``    ``}` `    ``// If the current state has already``    ``// been computed, then return it``    ``int` `val = dp[digit, mask, repeated];``    ``if` `(val != -1)``    ``{``        ``return` `val;``    ``}` `    ``// Stores the count of number for``    ``// the current recursive calls``    ``val = 0;` `    ``// If current position is 1, then``    ``// any digit can be placed.` `    ``// If n = 1, 0 can be also placed``    ``if` `(digit == 1)``    ``{``        ``for``(``int` `i = (n == 1 ? 0 : 1); i <= 9; ++i)``        ``{``            ` `            ``// If a digit has occurred``            ``// for the second time, then``            ``// set repeated to 1``            ``if` `((mask & (1 << i)) > 0)``            ``{``                ``val += countOfNumbers(``                    ``digit + 1, mask | (1 << i), 1, n);``            ``}` `            ``// Otherwise``            ``else``            ``{``                ``val += countOfNumbers(``                    ``digit + 1, mask | (1 << i), 0, n);``            ``}``        ``}``    ``}` `    ``// For remaining positions any``    ``// digit can be placed``    ``else``    ``{``        ``for``(``int` `i = 0; i <= 9; ++i)``        ``{``            ` `            ``// If a digit has occurred``            ``// for the second time, then``            ``// set repeated to 1``            ``if` `((mask & (1 << i)) > 0)``            ``{``                ``val += countOfNumbers(``                    ``digit + 1, mask | (1 << i), 1, n);``            ``}``            ``else``            ``{``                ``val += countOfNumbers(``                    ``digit + 1, mask | (1 << i), 0, n);``            ``}``        ``}``    ``}` `    ``// Return the resultant count for``    ``// the current recursive call``    ``return` `val;``}` `// Function to count all the N-digit``// numbers having at least one digit's``// occurrence more than once``public` `static` `void` `countNDigitNumber(``int` `N)``{``    ` `    ``// Initialize dp array with -1``    ``for``(``int` `i = 0; i < 50; i++)``    ``{``        ``for``(``int` `j = 0; j < 1 << 10; j++)``        ``{``            ``for``(``int` `k = 0; k < 2; k++)``            ``{``                ``dp[i, j, k] = -1;``            ``}``        ``}``    ``}` `    ``// Function to count all possible``    ``// number satisfying the given``    ``// criteria``    ``Console.Write(countOfNumbers(1, 0, 0, N));``}` `// Driver Code``public` `static` `void` `Main()``{``    ``int` `N = 2;``    ` `    ``countNDigitNumber(N);``}``}` `// This code is contributed by ukasp`

## Javascript

 ``
Output:
`9`

Time Complexity: O(10 * N * 210 * 2 )
Auxiliary Space: O(N * 210 * 2)

My Personal Notes arrow_drop_up