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 others can be a dynamic programming based solution. Below is a detailed approach to solving this problem using digit dynamic programming.Â
Dynamic Programming Solution: Firstly, if we are able to count the required numbers up to 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 up to 1018. In each recursive call, we try to build the sequence from left to right by placing a digit from 0 to 9.
- The 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.
- The 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, the maximum limit of digit we can place is digit at the current position in R.
In each recursive call, we set the last digit as the digit we placed in the last position, and we set the 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++
// C++ 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, tightint dp[M][M][M][2];Â
// This function returns the count of// required numbers from 0 to numint 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 answerint 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 Codeint 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;} |
Java
// Java program to find the count of // numbers in a range where the number // does not contain more than K non // zero digitsimport java.util.Collections;import java.util.Vector;import java.io.*;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 |
Python3
# Python3 code for above approachÂ
# Returns the count of numbers in range# if the first digit is equal to last digit of numberdef count(l, r):    cnt = 0      # Initialize counter    for i in range(l, r):                 # If number is less than 10        # then increment counter        # as number has only one digit         if(i < 10):                cnt += 1                     else:            n = i % 10    # Find the last digit            k = iÂ
            # Find the first digit            while(k >= 10):                k = k // 10Â
            # If first digit equals last digit            # then increment counter            if(n == k):                cnt += 1                     return(cnt)    # Return the countÂ
# Driver CodeL = 2; R = 60;print(count(L, R)) Â
L = 1; R = 1000;print(count(L, R))Â
# This code is contributed by Raj |
C#
// C# program to find the count of // numbers in a range where the number // does not contain more than K non // zero digitsusing System;using System.Collections.Generic;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 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,                      List<int> num)     { Â
        // Last position         if (pos == num.Count)         { Â
            // 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[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[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)     {         List<int> num = new List<int>();         while (x > 0)         {             num.Add(x % 10);             x /= 10;         } Â
        num.Reverse();Â
        // 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;         Console.WriteLine(solve(R) - solve(L - 1)); Â
        L = 1;         R = 1000;         Console.WriteLine(solve(R) - solve(L - 1));     } } Â
// This code is contributed by 29AjayKumar |
Javascript
<script>Â
// Javascript program to find the count of// numbers in a range where the number// does not contain more than K non// zero digitsÂ
let M = 20;Â
// states - position, first digit,    // last digit, tightlet 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(M);        for(let k=0;k<M;k++)            dp[i][j][k]=new Array(2);    }}Â
// This function returns the count of    // required numbers from 0 to numfunction count(pos,firstD,lastD,tight, num){    // Last position        if (pos == num.length)        {              // 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];        let 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]        let limit = (tight == 1 ? 9 : num[pos]);          for (let dig = 0; dig <= limit; dig++)        {            let 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;              let 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 answerfunction solve(x){    let num = [];        while (x > 0)        {            num.push(x % 10);            x = Math.floor(x/10);        }          num.reverse();          // Initialize dp        for (let i = 0; i < M; i++)            for (let j = 0; j < M; j++)                for (let k = 0; k < M; k++)                    for (let l = 0; l < 2; l++)                        dp[i][j][k][l] = -1;          return count(0, 0, 0, 0, num);}Â
// Driver Codelet L = 2, R = 60;document.write(solve(R) - solve(L - 1)+"<br>");Â
L = 1;R = 1000;document.write(solve(R) - solve(L - 1)+"<br>");Â
Â
// This code is contributed by rag2127Â
</script> |
13 108
Time Complexity : O(18 * 10 * 10 * 2 * 10), if we are dealing with the numbers upto 1018
 Auxiliary Space: O(20*20*20*2).
Alternative approach:
We can also solve this problem by recursion, for every position we can fill any number which satisfies the given condition except for the first and last position because they will be paired together, and for this, we will use recursion and in every call just check if the first number is smaller or larger than the last number if it turns out to be greater than we will add 8 otherwise 9 and call for number / 10, once the number becomes smaller than 10 first and the last digit becomes same so return the number itself.
Steps to solve the problem:
- Initialize the variables ans, first, last, and temp to 0 and the input variable x to a given value.
- Check if the value of x is less than 10. If true, return x as the output.
- Calculate the last digit of the given number x and store it in the variable last as last=x%10.
- While x is not equal to zero:
- update first as x%10.
- update x as x/10.
- Â Check if the value of first is less than or equal to the value of last. If true, ans=9+temp/10. Otherwise,ans=8+temp/10 .
- Â Return ans.
Below is the implementation of the above approach
C++
// C++ program to implement// the above approach#include <iostream>using namespace std;Â
int solve(int x){Â
    int ans = 0, first, last, temp = x;Â
    // Base CaseÂ
    if (x < 10)        return x;Â
    // Calculating the last digit    last = x % 10;Â
    // Calculating the first digit    while (x) {        first = x % 10;        x /= 10;    }Â
    if (first <= last)        ans = 9 + temp / 10;    else        ans = 8 + temp / 10;Â
    return ans;}Â
// Drivers Codeint 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;} |
Java
// Java program to implement// the above approachimport java.io.*;public class GFG{Â Â Â Â public static int solve(int x){Â Â int ans = 0, first = 0, Â Â Â Â Â Â last, temp = x;Â
  // Base Case  if (x < 10)    return x;Â
  // Calculating the   // last digit  last = x % 10;Â
  // Calculating the   // first digit  while (x != 0)   {    first = x % 10;    x /= 10;  }Â
  if (first <= last)    ans = 9 + temp / 10;  else    ans = 8 + temp / 10;Â
  return ans;}     // Driver codepublic 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 divyeshrabadiya07 |
Python3
# Python3 program to implement # the above approach def solve(x): Â
    ans, temp = 0, x          # Base Case     if (x < 10):         return x Â
    # Calculating the last digit     last = x % 10Â
    # Calculating the first digit     while (x):        first = x % 10        x = x // 10Â
    if (first <= last):        ans = 9 + temp // 10    else:        ans = 8 + temp // 10Â
    return ansÂ
# Driver CodeL, R = 2, 60print(solve(R) - solve(L - 1)) Â
L, R = 1, 1000print(solve(R) - solve(L - 1)) Â
# This code is contributed by divyesh072019 |
C#
// C# program to implement// the above approachusing System;Â
class GFG{     public static int solve(int x){    int ans = 0, first = 0,         last, temp = x;             // Base Case    if (x < 10)        return x;         // Calculating the     // last digit    last = x % 10;         // Calculating the     // first digit    while (x != 0)     {        first = x % 10;        x /= 10;    }         if (first <= last)        ans = 9 + temp / 10;    else        ans = 8 + temp / 10;         return ans;}     // Driver codepublic static void Main(String[] args) {    int L = 2, R = 60;    Console.WriteLine(solve(R) -                       solve(L - 1));         L = 1; R = 1000;    Console.WriteLine(solve(R) -                       solve(L - 1));}}Â
// This code is contributed by shivanisinghss2110 |
Javascript
<script>    // Javascript program to implement    // the above approach    function solve(x)    {Â
        let ans = 0, first, last, temp = x;Â
        // Base CaseÂ
        if (x < 10)            return x;Â
        // Calculating the last digit        last = x % 10;Â
        // Calculating the first digit        while (x > 0)        {            first = x % 10;            x /= 10;        }Â
        if (first <= last)            ans = 9 + temp / 10;        else            ans = 8 + temp / 10;Â
        return ans;    }Â
    let L = 2, R = 60;    document.write((solve(R) - solve(L - 1)) + "</br>");      L = 1, R = 1000;    document.write(solve(R) - solve(L - 1));         // This code is contributed by suresh07.</script> |
13 108
Time Complexity: O(log10(max(L,R))).
Auxiliary Space: O(1).
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



