Count of Numbers in Range where first digit is equal to last digit of the number

Given a range represented by two positive integers L and R. Find the count of numbers in the range where the first digit is equal to the last digit of the number.

Examples:

Input : L = 2, R = 60
Output : 13
Explanation : Required numbers are 
2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44 and 55

Input : L = 1, R = 1000
Output : 108

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.
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 firstD which defines the first digit of the number we are trying to build and can have values from 0 to 9.
  • Third state is the lastD which defines the last digit of the number we are trying to build and can have values from 0 to 9.
  • 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 each recursive call, we set last digit as the digit we placed in the last position and we set first digit as the first non zero digit of the number. In the final recursive call, when we are at the last position if the first digit is equal to the last digit, return 1, otherwise 0.

Below is the implementation of the above approach.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP Program to find the count of
// numbers in a range where the number
// does not contain more than K non
// zero digits
  
#include <bits/stdc++.h>
  
using namespace std;
  
const int M = 20;
  
// states - position, first digit,
// last digit, tight
int dp[M][M][M][2];
  
// This function returns the count of
// required numbers from 0 to num
int count(int pos, int firstD, int lastD,
        int tight, vector<int> num)
{
    // Last position
    if (pos == num.size()) {
  
        // If first digit is equal to
        // last digit
        if (firstD == lastD)
            return 1;
        return 0;
    }
  
    // If this result is already computed
    // simply return it
    if (dp[pos][firstD][lastD][tight] != -1)
        return dp[pos][firstD][lastD][tight];
  
    int ans = 0;
  
    // Maximum limit upto which we can place
    // digit. If tight is 1, means number has
    // already become smaller so we can place
    // any digit, otherwise num[pos]
    int limit = (tight ? 9 : num[pos]);
  
    for (int dig = 0; dig <= limit; dig++) {
        int currFirst = firstD;
  
        // If the position is 0, current
        // digit can be first digit
        if (pos == 0)
            currFirst = dig;
  
        // In current call, if the first
        // digit is zero and current digit
        // is nonzero, update currFirst
        if (!currFirst && dig)
            currFirst = dig;
  
        int currTight = tight;
  
        // At this position, number becomes
        // smaller
        if (dig < num[pos])
            currTight = 1;
  
        // Next recursive call, set last
        // digit as dig
        ans += count(pos + 1, currFirst,
                    dig, currTight, num);
    }
    return dp[pos][firstD][lastD][tight] = ans;
}
  
// This function converts a number into its
// digit vector and uses above function to compute
// the answer
int solve(int x)
{
    vector<int> num;
    while (x) {
        num.push_back(x % 10);
        x /= 10;
    }
    reverse(num.begin(), num.end());
  
    // Initialize dp
    memset(dp, -1, sizeof(dp));
    return count(0, 0, 0, 0, num);
}
  
// Driver Code
int main()
{
    int L = 2, R = 60;
    cout << solve(R) - solve(L - 1) << endl;
  
    L = 1, R = 1000;
    cout << solve(R) - solve(L - 1) << endl;
      
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find the count of 
// numbers in a range where the number 
// does not contain more than K non 
// zero digits
import java.util.Collections;
import java.util.Vector;
  
class GFG 
{
    static int M = 20;
  
    // states - position, first digit,
    // last digit, tight
    static int[][][][] dp = new int[M][M][M][2];
  
    // This function returns the count of
    // required numbers from 0 to num
    static int count(int pos, int firstD, 
                     int lastD, int tight, 
                     Vector<Integer> num) 
    {
  
        // Last position
        if (pos == num.size())
        {
  
            // If first digit is equal to
            // last digit
            if (firstD == lastD)
                return 1;
            return 0;
        }
  
        // If this result is already computed
        // simply return it
        if (dp[pos][firstD][lastD][tight] != -1)
            return dp[pos][firstD][lastD][tight];
        int ans = 0;
  
        // Maximum limit upto which we can place
        // digit. If tight is 1, means number has
        // already become smaller so we can place
        // any digit, otherwise num[pos]
        int limit = (tight == 1 ? 9 : num.elementAt(pos));
  
        for (int dig = 0; dig <= limit; dig++)
        {
            int currFirst = firstD;
  
            // If the position is 0, current
            // digit can be first digit
            if (pos == 0)
                currFirst = dig;
  
            // In current call, if the first
            // digit is zero and current digit
            // is nonzero, update currFirst
            if (currFirst == 0 && dig != 0)
                currFirst = dig;
  
            int currTight = tight;
  
            // At this position, number becomes
            // smaller
            if (dig < num.elementAt(pos))
                currTight = 1;
  
            // Next recursive call, set last
            // digit as dig
            ans += count(pos + 1, currFirst, 
                         dig, currTight, num);
        }
        return dp[pos][firstD][lastD][tight] = ans;
    }
  
    // This function converts a number into its
    // digit vector and uses above function to 
    // compute the answer
    static int solve(int x) 
    {
        Vector<Integer> num = new Vector<>();
        while (x > 0
        {
            num.add(x % 10);
            x /= 10;
        }
  
        Collections.reverse(num);
  
        // Initialize dp
        for (int i = 0; i < M; i++)
            for (int j = 0; j < M; j++)
                for (int k = 0; k < M; k++)
                    for (int l = 0; l < 2; l++)
                        dp[i][j][k][l] = -1;
  
        return count(0, 0, 0, 0, num);
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        int L = 2, R = 60;
        System.out.println(solve(R) - solve(L - 1));
  
        L = 1;
        R = 1000;
        System.out.println(solve(R) - solve(L - 1));
    }
}
  
// This code is contributed by
// sanjeev2552

chevron_right


Output:

13
108

Time Complexity : O(18 * 10 * 10 * 2 * 10), if we are dealing with the numbers upto 1018



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : sanjeev2552