Given a range represented by two positive integers L and R and a positive integer K. Find the count of numbers in the range where the number does not contain more than K non zero digits.
Examples:
Input : L = 1, R = 1000, K = 3
Output : 1000
Explanation : All the numbers from 1 to 1000
are 3 digit numbers which obviously cannot
contain more than 3 non zero digits.
Input : L = 9995, R = 10005
Output : 6
Explanation : Required numbers are
10000, 10001, 10002, 10003, 10004 and 10005
Prerequisites : Digit DP
There can be two approaches to solve this type of problem, one can be a combinatorial solution and other can be a dynamic programming based solution. Below is a detailed approach of solving this problem using a digit dynamic programming approach.
Dynamic Programming Solution : Firstly, if we are able to count the required numbers upto R i.e. in the range [0, R], we can easily reach our answer in the range [L, R] by solving for from zero to R and then subtracting the answer we get after solving for from zero to L – 1. Now, we need to define the DP states.
DP States:
- Since we can consider our number as a sequence of digits, one state is the position at which we are currently in. This position can have values from 0 to 18 if we are dealing with the numbers upto 1018. In each recursive call, we try to build the sequence from left to right by placing a digit from 0 to 9.
- Second state is the count which defines the number of non zero digits, we have placed in the number we are trying to build.
- Another state is the boolean variable tight which tells the number we are trying to build has already become smaller than R, so that in the upcoming recursive calls we can place any digit from 0 to 9. If the number has not become smaller, maximum limit of digit we can place is digit at current position in R.
In the final recursive call, when we are at the last position if the count of non zero digits is less than or equal to K, return 1 otherwise return 0.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
const int M = 20;
int dp[M][M][2];
int K;
int countInRangeUtil( int pos, int cnt, int tight,
vector< int > num)
{
if (pos == num.size()) {
if (cnt <= K)
return 1;
return 0;
}
if (dp[pos][cnt][tight] != -1)
return dp[pos][cnt][tight];
int ans = 0;
int limit = (tight ? 9 : num[pos]);
for ( int dig = 0; dig <= limit; dig++) {
int currCnt = cnt;
if (dig != 0)
currCnt++;
int currTight = tight;
if (dig < num[pos])
currTight = 1;
ans += countInRangeUtil(pos + 1, currCnt,
currTight, num);
}
return dp[pos][cnt][tight] = ans;
}
int countInRange( int x)
{
vector< int > num;
while (x) {
num.push_back(x % 10);
x /= 10;
}
reverse(num.begin(), num.end());
memset (dp, -1, sizeof (dp));
return countInRangeUtil(0, 0, 0, num);
}
int main()
{
int L = 1, R = 1000;
K = 3;
cout << countInRange(R) - countInRange(L - 1) << endl;
L = 9995, R = 10005, K = 2;
cout << countInRange(R) - countInRange(L - 1) << endl;
return 0;
}
|
Java
import java.util.*;
class Solution
{
static final int M = 20 ;
static int dp[][][]= new int [M][M][ 2 ];
static int K;
static Vector<Integer> num;
static int countInRangeUtil( int pos, int cnt, int tight )
{
if (pos == num.size()) {
if (cnt <= K)
return 1 ;
return 0 ;
}
if (dp[pos][cnt][tight] != - 1 )
return dp[pos][cnt][tight];
int ans = 0 ;
int limit = (tight!= 0 ? 9 : num.get(pos));
for ( int dig = 0 ; dig <= limit; dig++) {
int currCnt = cnt;
if (dig != 0 )
currCnt++;
int currTight = tight;
if (dig < num.get(pos))
currTight = 1 ;
ans += countInRangeUtil(pos + 1 , currCnt, currTight);
}
return dp[pos][cnt][tight] = ans;
}
static int countInRange( int x)
{
num= new Vector<Integer>();
while (x!= 0 ) {
num.add(x % 10 );
x /= 10 ;
}
Collections.reverse(num);
for ( int i= 0 ;i<M;i++)
for ( int j= 0 ;j<M;j++)
for ( int k= 0 ;k< 2 ;k++)
dp[i][j][k]=- 1 ;
return countInRangeUtil( 0 , 0 , 0 );
}
public static void main(String args[])
{
int L = 1 , R = 1000 ;
K = 3 ;
System.out.println( countInRange(R) - countInRange(L - 1 ) );
L = 9995 ; R = 10005 ; K = 2 ;
System.out.println( countInRange(R) - countInRange(L - 1 ) );
}
}
|
Python3
def countInRangeUtil(pos, cnt, tight, num):
if pos = = len (num):
if cnt < = K:
return 1
return 0
if dp[pos][cnt][tight] ! = - 1 :
return dp[pos][cnt][tight]
ans = 0
limit = 9 if tight else num[pos]
for dig in range (limit + 1 ):
currCnt = cnt
if dig ! = 0 :
currCnt + = 1
currTight = tight
if dig < num[pos]:
currTight = 1
ans + = countInRangeUtil(pos + 1 , currCnt, currTight, num)
dp[pos][cnt][tight] = ans
return dp[pos][cnt][tight]
def countInRange(x):
global dp, K, M
num = []
while x:
num.append(x % 10 )
x / / = 10
num.reverse()
dp = [[[ - 1 , - 1 ] for i in range (M)] for j in range (M)]
return countInRangeUtil( 0 , 0 , 0 , num)
if __name__ = = "__main__" :
dp = []
M = 20
K = 0
L = 1
R = 1000
K = 3
print (countInRange(R) - countInRange(L - 1 ))
L = 9995
R = 10005
K = 2
print (countInRange(R) - countInRange(L - 1 ))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int M = 20;
static int [,,]dp = new int [M, M, 2];
static int K;
static List< int > num;
static int countInRangeUtil( int pos,
int cnt, int tight )
{
if (pos == num.Count)
{
if (cnt <= K)
return 1;
return 0;
}
if (dp[pos, cnt, tight] != -1)
return dp[pos, cnt, tight];
int ans = 0;
int limit = (tight != 0 ? 9 : num[pos]);
for ( int dig = 0; dig <= limit; dig++)
{
int currCnt = cnt;
if (dig != 0)
currCnt++;
int currTight = tight;
if (dig < num[pos])
currTight = 1;
ans += countInRangeUtil(pos + 1, currCnt, currTight);
}
return dp[pos,cnt,tight] = ans;
}
static int countInRange( int x)
{
num = new List< int >();
while (x != 0)
{
num.Add(x % 10);
x /= 10;
}
num.Reverse();
for ( int i = 0; i < M; i++)
for ( int j = 0; j < M; j++)
for ( int k = 0; k < 2; k++)
dp[i, j, k] = -1;
return countInRangeUtil(0, 0, 0);
}
public static void Main()
{
int L = 1, R = 1000;
K = 3;
Console.WriteLine( countInRange(R) - countInRange(L - 1) );
L = 9995; R = 10005; K = 2;
Console.WriteLine( countInRange(R) - countInRange(L - 1) );
}
}
|
Javascript
<script>
let M = 20;
let dp = new Array(M);
for (let i = 0; i < M; i++)
{
dp[i] = new Array(M);
for (let j = 0; j < M; j++)
{
dp[i][j] = new Array(2);
for (let k = 0; k < 2; k++)
dp[i][j][k] = 0;
}
}
let K;
let num;
function countInRangeUtil(pos, cnt, tight )
{
if (pos == num.length)
{
if (cnt <= K)
return 1;
return 0;
}
if (dp[pos][cnt][tight] != -1)
return dp[pos][cnt][tight];
let ans = 0;
let limit = (tight!=0 ? 9 : num[pos]);
for (let dig = 0; dig <= limit; dig++) {
let currCnt = cnt;
if (dig != 0)
currCnt++;
let currTight = tight;
if (dig < num[pos])
currTight = 1;
ans += countInRangeUtil(pos + 1, currCnt, currTight);
}
return dp[pos][cnt][tight] = ans;
}
function countInRange(x)
{
num= [];
while (x!=0) {
num.push(x % 10);
x = Math.floor(x/10);
}
num.reverse();
for (let i=0;i<M;i++)
for (let j=0;j<M;j++)
for (let k=0;k<2;k++)
dp[i][j][k]=-1;
return countInRangeUtil(0, 0, 0);
}
let L = 1, R = 1000;
K = 3;
document.write( (countInRange(R) - countInRange(L - 1)) + "<br>" );
L = 9995; R = 10005; K = 2;
document.write( (countInRange(R) - countInRange(L - 1)) + "<br>" );
</script>
|
Time Complexity : O(M * M * 2 * 10) where M = log(MAX), here MAX is the maximum number.
Auxiliary Space: O(M*M)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!