The Wayback Machine - https://web.archive.org/web/20241008142211/https://www.geeksforgeeks.org/digit-dp-introduction/
Open In App

Digit DP | Introduction

Last Updated : 17 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite : How to solve a Dynamic Programming Problem ?
There are many types of problems that ask to count the number of integers ‘x‘ between two integers say ‘a‘ and ‘b‘ such that x satisfies a specific property that can be related to its digits.
So, if we say G(x) tells the number of such integers between 1 to x (inclusively), then the number of such integers between a and b can be given by G(b) – G(a-1). This is when Digit DP (Dynamic Programming) comes into action. All such integer counting problems that satisfy the above property can be solved by digit DP approach.
 

Key Concept:

  • Let given number x has n digits. The main idea of digit DP is to first represent the digits as an array of digits t[]. Let’s say a we have tntn-1tn-2 … t2t1 as the decimal representation where ti (0 < i <= n) tells the i-th digit from the right. The leftmost digit tn is the most significant digit. 
     
  • Now, after representing the given number this way we generate the numbers less than the given number and simultaneously calculate using DP, if the number satisfy the given property. We start generating integers having number of digits = 1 and then till number of digits = n. Integers having less number of digits than n can be analyzed by setting the leftmost digits to be zero. 
     

Example Problem : 
Given two integers a and b. Your task is to print the sum of 
all the digits appearing in the integers between a and b.
For example if a = 5 and b = 11, then answer is 38 (5 + 6 + 7 + 8 + 9 + 1 + 0 + 1 + 1)
Constraints : 1 <= a < b <= 10^18
Now we see that if we have calculated the answer for state having n-1 digits, i.e., tn-1 tn-2 … t2 t1 and we need to calculate answer for state having n digits tn tn-1 tn-2 … t2 t1. So, clearly, we can use the result of the previous state instead of re-calculating it. Hence, it follows the overlapping property.
Let’s think for a state for this DP
Our DP state will be dp(idx, tight, sum)
1) idx  

  • It tells about the index value from right in the given integer

2) tight  

  • This will tell if the current digits range is restricted or not. If the current digit’s 
    range is not restricted then it will span from 0 to 9 (inclusively) else it will span 
    from 0 to digit[idx] (inclusively).
    Example: consider our limiting integer to be 3245 and we need to calculate G(3245) 
    index : 4 3 2 1 
    digits : 3 2 4 5 
     

Unrestricted range: 
Now suppose the integer generated till now is : 3 1 * * ( * is empty place, where digits are to be inserted to form the integer). 

  index  : 4 3 2 1  
  digits : 3 2 4 5
 generated integer: 3 1 _ _ 

here, we see that index 2 has unrestricted range. Now index 2 can have digits from range 0 to 9(inclusively). 
For unrestricted range tight = 0
Restricted range: 
Now suppose the integer generated till now is : 3 2 * * ( ‘*’ is an empty place, where digits are to be inserted to form the integer). 

  index  : 4 3 2 1  
  digits : 3 2 4 5
 generated integer: 3 2 _ _ 

here, we see that index 2 has a restricted range. Now index 2 can only have digits from range 0 to 4 (inclusively) 
For restricted range tight = 1
3) sum 

  • This parameter will store the sum of digits in the generated integer from msd to idx. 
     
  • Max value for this parameter sum can be 9*18 = 162, considering 18 digits in the integer

State Relation:
The basic idea for state relation is very simple. We formulate the dp in top-down fashion. 
Let’s say we are at the msd having index idx. So initially the sum will be 0.
Therefore, we will fill the digit at index by the digits in its range. Let’s say its range is from 0 to k (k<=9, depending on the tight value) and fetch the answer from the next state having index = idx-1 and sum = previous sum + digit chosen. 

int ans = 0;
for (int i=0; i<=k; i++) {
   ans += state(idx-1, newTight, sum+i)
}

state(idx,tight,sum) = ans;

How to calculate the newTight value? 
The new tight value from a state depends on its previous state. If tight value form the previous state is 1 and the digit at idx chosen is digit[idx](i.e the digit at idx in limiting integer) , then only our new tight will be 1 as it only then tells that the number formed till now is prefix of the limiting integer. 

// digitTaken is the digit chosen
// digit[idx] is the digit in the limiting 
//            integer at index idx from right
// previouTight is the tight value form previous 
//              state

newTight = previousTight & (digitTake == digit[idx])

Below is the implementation of the above approach

CPP




// Given two integers a and b. The task is to print
// sum of all the digits appearing in the
// integers between a and b
#include "bits/stdc++.h"
using namespace std;
 
// Memoization for the state results
long long dp[20][180][2];
 
// Stores the digits in x in a vector digit
void getDigits(long long x, vector <int> &digit;)
{
    while (x)
    {
        digit.push_back(x%10);
        x /= 10;
    }
}
 
// Return sum of digits from 1 to integer in
// digit vector
long long digitSum(int idx, int sum, int tight,
                          vector <int> &digit;)
{
    // base case
    if (idx == -1)
       return sum;
 
    // checking if already calculated this state
    if (dp[idx][sum][tight] != -1 and tight != 1)
        return dp[idx][sum][tight];
 
    long long ret = 0;
 
    // calculating range value
    int k = (tight)? digit[idx] : 9;
 
    for (int i = 0; i <= k ; i++)
    {
        // calculating newTight value for next state
        int newTight = (digit[idx] == i)? tight : 0;
 
        // fetching answer from next state
        ret += digitSum(idx-1, sum+i, newTight, digit);
    }
 
    if (!tight)
      dp[idx][sum][tight] = ret;
 
    return ret;
}
 
// Returns sum of digits in numbers from a to b.
int rangeDigitSum(int a, int b)
{
    // initializing dp with -1
    memset(dp, -1, sizeof(dp));
 
    // storing digits of a-1 in digit vector
    vector<int> digitA;
    getDigits(a-1, digitA);
 
    // Finding sum of digits from 1 to "a-1" which is passed
    // as digitA.
    long long ans1 = digitSum(digitA.size()-1, 0, 1, digitA);
 
    // Storing digits of b in digit vector
    vector<int> digitB;
    getDigits(b, digitB);
 
    // Finding sum of digits from 1 to "b" which is passed
    // as digitB.
    long long ans2 = digitSum(digitB.size()-1, 0, 1, digitB);
 
    return (ans2 - ans1);
}
 
// driver function to call above function
int main()
{
    long long a = 123, b = 1024;
    cout << "digit sum for given range : "
         << rangeDigitSum(a, b) << endl;
    return 0;
}


Java




// Java program for above approach
 
import java.util.ArrayList;
import java.util.Arrays;
 
// Given two integers a and b. The task is to print
// sum of all the digits appearing in the
// integers between a and b
public class GFG {
 
    // Memoization for the state results
    static long dp[][][] = new long[20][180][2];
 
    // Stores the digits in x in a vector digit
    static void getDigits(long x, ArrayList<Integer> digit)
    {
        while (x != 0) {
            digit.add((int)(x % 10));
            x /= 10;
        }
    }
 
    // Return sum of digits from 1 to integer in
    // digit vector
    static long digitSum(int idx, int sum, int tight,
                         ArrayList<Integer> digit)
    {
        // base case
        if (idx == -1)
            return sum;
 
        // checking if already calculated this state
        if (dp[idx][sum][tight] != -1 && tight != 1)
            return dp[idx][sum][tight];
 
        long ret = 0;
 
        // calculating range value
        int k = (tight != 0) ? digit.get(idx) : 9;
 
        for (int i = 0; i <= k; i++) {
            // calculating newTight value for next state
            int newTight
                = (digit.get(idx) == i) ? tight : 0;
 
            // fetching answer from next state
            ret += digitSum(idx - 1, sum + i, newTight,
                            digit);
        }
 
        if (tight != 0)
            dp[idx][sum][tight] = ret;
 
        return ret;
    }
 
    // Returns sum of digits in numbers from a to b.
    static int rangeDigitSum(int a, int b)
    {
        // initializing dp with -1
        for (int i = 0; i < 20; i++)
            for (int j = 0; j < 180; j++)
                for (int k = 0; k < 2; k++)
                    dp[i][j][k] = -1;
 
        // storing digits of a-1 in digit vector
        ArrayList<Integer> digitA
            = new ArrayList<Integer>();
        getDigits(a - 1, digitA);
 
        // Finding sum of digits from 1 to "a-1" which is
        // passed as digitA.
        long ans1
            = digitSum(digitA.size() - 1, 0, 1, digitA);
 
        // Storing digits of b in digit vector
        ArrayList<Integer> digitB
            = new ArrayList<Integer>();
        getDigits(b, digitB);
 
        // Finding sum of digits from 1 to "b" which is
        // passed as digitB.
        long ans2
            = digitSum(digitB.size() - 1, 0, 1, digitB);
 
        return (int)(ans2 - ans1);
    }
 
    // driver function to call above function
    public static void main(String[] args)
    {
        int a = 123, b = 1024;
        System.out.println("digit sum for given range : "
                           + rangeDigitSum(a, b));
    }
}
 
// This code is contributed by Lovely Jain


Python3




# Given two integers a and b. The task is to
# print sum of all the digits appearing in the
# integers between a and b
 
# Memoization for the state results
dp = [[[-1 for i in range(2)] for j in range(180)]for k in range(20)]
 
# Stores the digits in x in a list digit
def getDigits(x, digit):
    while x:
        digit.append(x % 10)
        x //= 10
         
# Return sum of digits from 1 to integer in digit list
def digitSum(index, sumof, tight, digit):
   
    # Base case
    if index == -1:
        return sumof
       
        # Checking if already calculated this state
    if dp[index][sumof][tight] != -1 and tight != 1:
        return dp[index][sumof][tight]
    ret = 0
     
    # Calculating range value
    k = digit[index] if tight else 9
    for i in range(0, k+1):
       
        # Calculating newTight value for nextstate
        newTight = tight if digit[index] == i else 0
         
        # Fetching answer from next state
        ret += digitSum(index-1, sumof+i, newTight, digit)
    if not tight:
        dp[index][sumof][tight] = ret
    return ret
   
# Returns sum of digits in numbers from a to b
def rangeDigitSum(a, b):
    digitA = []
     
    # Storing digits of a-1 in digitA
    getDigits(a-1, digitA)
     
    # Finding sum of digits from 1 to "a-1" which is passed as digitA
    ans1 = digitSum(len(digitA)-1, 0, 1, digitA)
    digitB = []
     
    # Storing digits of b in digitB
    getDigits(b, digitB)
     
    # Finding sum of digits from 1 to "b" which is passed as digitB
    ans2 = digitSum(len(digitB)-1, 0, 1, digitB)
    return ans2-ans1
 
 
a, b = 123, 1024
print("digit sum for given range: ", rangeDigitSum(a, b))
 
# This code is contributed by rupasriachanta421


C#




// C# Code
using System;
using System.Collections.Generic;
 
namespace GFG {
  class Program {
    // Memoization for the state results
    static long[, , ] dp = new long[20, 180, 2];
 
    // Stores the digits in x in a vector digit
    static void getDigits(long x, List<int> digit)
    {
      while (x != 0) {
        digit.Add((int)(x % 10));
        x /= 10;
      }
    }
 
    // Return sum of digits from 1 to integer in
    // digit vector
    static long digitSum(int idx, int sum, int tight,
                         List<int> digit)
    {
      // base case
      if (idx == -1)
        return sum;
 
      // checking if already calculated this state
      if (dp[idx, sum, tight] != -1 && tight != 1)
        return dp[idx, sum, tight];
 
      long ret = 0;
 
      // calculating range value
      int k = (tight != 0) ? digit[idx] : 9;
 
      for (int i = 0; i <= k; i++) {
        // calculating newTight value for next state
        int newTight = (digit[idx] == i) ? tight : 0;
 
        // fetching answer from next state
        ret += digitSum(idx - 1, sum + i, newTight,
                        digit);
      }
 
      if (tight != 0)
        dp[idx, sum, tight] = ret;
 
      return ret;
    }
 
    // Returns sum of digits in numbers from a to b.
    static int rangeDigitSum(int a, int b)
    {
      // initializing dp with -1
      for (int i = 0; i < 20; i++)
        for (int j = 0; j < 180; j++)
          for (int k = 0; k < 2; k++)
            dp[i, j, k] = -1;
 
      // storing digits of a-1 in digit vector
      List<int> digitA = new List<int>();
      getDigits(a - 1, digitA);
 
      // Finding sum of digits from 1 to "a-1" which is
      // passed as digitA.
      long ans1
        = digitSum(digitA.Count - 1, 0, 1, digitA);
 
      // Storing digits of b in digit vector
      List<int> digitB = new List<int>();
      getDigits(b, digitB);
 
      // Finding sum of digits from 1 to "b" which is
      // passed as digitB.
      long ans2
        = digitSum(digitB.Count - 1, 0, 1, digitB);
 
      return (int)(ans2 - ans1);
    }
 
    // driver function to call above function
    public static void Main(String[] args)
    {
      int a = 123, b = 1024;
      Console.WriteLine("digit sum for given range : "
                        + rangeDigitSum(a, b));
    }
  }
}
 
// This code is contributed by ishankhandelwals.


Javascript




// Given two integers a and b. The task is to print
// sum of all the digits appearing in the
// integers between a and b
 
// Memoization for the state results
let dp = [];
 
// Stores the digits in x in a array digit
function getDigits(x, digit) {
  while (x) {
    digit.push(x % 10);
    x = Math.floor(x / 10);
  }
}
 
// Return sum of digits from 1 to integer in
// digit array
function digitSum(idx, sum, tight, digit) {
  // base case
  if (idx === -1) return sum;
 
  // checking if already calculated this state
  if (dp[idx] && dp[idx][sum] && dp[idx][sum][tight] != null && tight !== 1) {
    return dp[idx][sum][tight];
  }
 
  let ret = 0;
 
  // calculating range value
  let k = tight ? digit[idx] : 9;
 
  for (let i = 0; i <= k; i++) {
    // calculating newTight value for next state
    let newTight = digit[idx] === i ? tight : 0;
 
    // fetching answer from next state
    ret += digitSum(idx - 1, sum + i, newTight, digit);
  }
 
  if (tight !== 1) {
    dp[idx] = dp[idx] || [];
    dp[idx][sum] = dp[idx][sum] || [];
    dp[idx][sum][tight] = ret;
  }
 
  return ret;
}
 
// Returns sum of digits in numbers from a to b.
function rangeDigitSum(a, b) {
  // initializing dp with null
  dp = [];
 
  // storing digits of a-1 in digit array
  let digitA = [];
  getDigits(a - 1, digitA);
 
  // Finding sum of digits from 1 to "a-1" which is passed
  // as digitA.
  let ans1 = digitSum(digitA.length - 1, 0, 1, digitA);
 
  // Storing digits of b in digit array
  let digitB = [];
  getDigits(b, digitB);
 
  // Finding sum of digits from 1 to "b" which is passed
  // as digitB.
  let ans2 = digitSum(digitB.length - 1, 0, 1, digitB);
 
  return ans2 - ans1;
}
 
// driver function to call above function
function main() {
  let a = 123,
    b = 1024;
  console.log("digit sum for given range : " + rangeDigitSum(a, b));
}
 
main();
// This code is contributed by divyansh2212


Output:

digit sum for given range : 12613

Time Complexity:
There are total idx*sum*tight states and we are performing 0 to 9 iterations to visit every state. Therefore, The Time Complexity will be O(10*idx*sum*tight). Here, we observe that tight = 2 and idx can be max 18 for 64 bit unsigned integer and moreover, the sum will be max 9*18 ~ 200. So, overall we have 10*18*200*2 ~ 10^5 iterations which can be easily executed in 0.01 seconds.

Space Complexity:

The space complexity of this algorithm is O(d*sum*tight) as it uses a dp array of size d*sum*tight. where d is the number of digits in the number, sum is the sum of the digits and tight is a boolean value indicating whether or not the current digit is restricted to the digit in the number or not. 

The above problem can also be solved using simple recursion without any memoization. The recursive solution for the above problem can be found here. We will be soon adding more problems on digit dp in our future posts.



Previous Article
Next Article

Similar Reads

Count of N-digit numbers having digit XOR as single digit
Given an integer N, the task is to find the total count of N-Digit numbers such that the Bitwise XOR of the digits of the numbers is a single digit. Examples: Input: N = 1Output: 9Explanation: 1, 2, 3, 4, 5, 6, 7, 8, 9 are the numbers. Input: N = 2Output: 66Explanation: There are 66 such 2-digit numbers whose Xor of digits is a single digit number.
14 min read
Count ways to generate N digit number such that its every digit divisible by previous digit
Given a number N, the task is to count the number of ways to create an N digit number from digits 1 to 9 such that every digit is divisible by its previous digit that is if the number is represented by an array of digits A then A[i + 1] % A[i] == 0. print the answer modulo 109 + 7. Examples: Input: N = 2Output: 23Explanation: For N = 2 possible ans
15+ min read
Count n digit numbers not having a particular digit
We are given two integers n and d, we need to count all n digit numbers that do not have digit d. Example : Input : n = 2, d = 7 Output : 72 All two digit numbers that don't have 7 as digit are 10, 11, 12, 13, 14, 15, 16, 18, ..... Input : n = 3, d = 9 Output : 648 A simple solution is to traverse through all d digit numbers. For every number, chec
8 min read
Largest number less than N with digit sum greater than the digit sum of N
Given an integer N, the task is to find the greatest number less than N such that the sum of its digits is greater than the sum of the digits of N. If the condition isn't satisfied for any number then print -1.Examples: Input: N = 100 Output: 99 99 is the largest number less than 100 sum of whose digits is greater than the sum of the digits of 100I
9 min read
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 DPTh
15+ min read
Count numbers in a range with digit sum divisible by K having first and last digit different
Given a range in the form of L and R, and a value K, the task is to count the numbers between the range L to R such that the sum of the digit is divisible by K, and the first digit is not equal to the last digit of the number. Examples: Input: L = 1, R = 10, K = 2 Output: 0 Explanation: The input numbers whose sum of the digits are divisible by 2 (
15 min read
Find the remainder when First digit of a number is divided by its Last digit
Given a number N, find the remainder when the first digit of N is divided by its last digit.Examples: Input: N = 1234 Output: 1 First digit = 1 Last digit = 4 Remainder = 1 % 4 = 1 Input: N = 5223 Output: 2 First digit = 5 Last digit = 3 Remainder = 5 % 3 = 2 Approach: Find the first digit and the last digit of the number. Find then the remainder w
5 min read
Find all numbers between range L to R such that sum of digit and sum of square of digit is prime
Given the range L and R, count all numbers between L to R such that sum of digits of each number and sum of square of digits of each number is Prime.Note: 10 <= [L, R] <= 108 Examples: Input: L = 10, R = 20 Output: 4 Such types of numbers are: 11 12 14 16 Input: L = 100, R = 130 Output: 9Such types of numbers are : 101 102 104 106 110 111 113
9 min read
Count of pairs (A, B) in range 1 to N such that last digit of A is equal to the first digit of B
Given a number N, the task is to find the number of pairs (A, B) in the range [1, N] such that the last digit of A is equal to the first digit of B, and the first digit of A is equal to the last digit of B.Examples: Input: N = 25 Output: 17 Explanation: The pairs are: (1, 1), (1, 11), (2, 2), (2, 22), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8),
5 min read
Last digit of a number raised to last digit of N factorial
Given two number X and N, the task is to find the last digit of X raised to last digit of N factorial, i.e. [Tex]X^{\left ( N! \right )mod 10} [/Tex].Examples: Input: X = 5, N = 2 Output: 5 Explanation: Since, 2! mod 10 = 2 therefore 52 = 25 and the last digit of 25 is 5.Input: X = 10, N = 4 Output: 0 Explanation: Since, 4! mod 10 = 24 mod 10 = 4 t
15 min read
Min steps to convert N-digit prime number into another by replacing a digit in each step
Given two N-digit prime numbers A and B, the task is to find the minimum number of steps taken to convert A to B. Condition for the conversion is that only 1 digit of the current prime number can be modified such that the new number formed is also a prime number. If no such conversion is possible, print -1. Note: The range of N is [1, 5]. Examples:
12 min read
Count possible N-digit numbers such that each digit does not appear more than given number of times consecutively
Given an integer N and an array maxDigit[], the task is to count all the distinct N-digit numbers such that digit i does not appear more than maxDigit[i] times. Since the count can be very large, print it modulo 109 + 7. Examples: Input: N = 2, maxDigit[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}Output: 90Explanation:Any digit can't appear more than once co
15+ min read
Count of N-digit numbers having each digit as the mean of its adjacent digits
Given a positive integer N, the task is to count the number of N-digit numbers where each digit in the number is the mean of its two adjacent digits. Examples : Input: N = 1Output: 10Explanation: All numbers from 0 to 9 satisfy the given condition as there is only one digit. Input: N = 2Output: 90 Naive Approach: The simplest approach to solve the
11 min read
Count N-digit numbers such that every position is divisible by the digit at that position
Given a positive integer N, the task is to count the number of N-digit numbers such that every index (1-based indexing) in the number is divisible by the digit occurring at that index. Since the court can be very large, print it modulo 109 + 7. Examples: Input: N = 2Output: 2Explanation: The numbers 11 and 12 are the only 2-digit numbers satisfying
6 min read
Count of N digit numbers which contains all single digit primes
Given a positive integer N, the task is to count the number of N-digit numbers which contain all single digit primes. Examples: Input: N = 4Output: 24Explanation: The number of single digit primes is 4 i.e.{2, 3, 5, 7}. Hence number of ways to arrange 4 numbers in 4 places is 4! = 24. Input: N = 5Output: 936 Naive Approach: The simplest approach to
12 min read
Count of integer whose factorial of digit sum contains every digit of original number
Given an array arr[] of length n which contains positive integers (0 ≤ arr[i] ≤ 109), the task is to count the number of elements present in the given array such that the factorial of their digit sum (we will do digit sum while its value is greater than 10) contains every digit present in the original integer. Examples: Input: arr[] = [653, 663, 24
14 min read
Count of N digit numbers with at least one digit as K
Given a number N and a digit K, The task is to count N digit numbers with at least one digit as K. Examples: Input: N = 3, K = 2Output: 252Explanation: For one occurrence of 2 - In a number of length 3, the following cases are possible:=>When first digit is 2 and other two digits can have 9 values except '2'. Thus 9*9 = 81 combination are possib
6 min read
Count N-digit numbers that contains every possible digit atleast once
Given a positive integer N, the task is to count the number of N-digit numbers such that every digit from [0-9] occurs at least once. Examples : Input: N = 10Output : 3265920 Input: N = 5Output: 0Explanation: Since the number of digits is less than the minimum number of digits required [0-9], the answer is 0. Naive Approach: The simplest approach t
15 min read
Count of N-digit numbers with at least one digit repeating
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: Input: N = 2Output: 9Explanation: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
15+ min read
Count 'd' digit positive integers with 0 as a digit
Given a number d, representing the number of digits of a positive integer. Find the total count of positive integer (consisting of d digits exactly) which have at-least one zero in them.Examples: Input : d = 1 Output : 0 There's no natural number of 1 digit that contains a zero. Input : d = 2 Output : 9 The numbers are, 10, 20, 30, 40, 50, 60, 70,
5 min read
Check if frequency of each digit is less than the digit
Given an integer n, the task is to check if frequency of each digit of the number is less than or equal to digit itself. Examples: Input : 51241 Output : False Input : 1425243 Output : True Naive Approach: Start from 0 and count the frequency for every digit upto 9, if at any place frequency is more than the digit value then return false, else retu
8 min read
Count all Pairs in an Array with Balanced Digit Sums and Even-Digit Concatenation
Given an array of integers arr[], A pairs (i, j) is valid, which follows the below two conditions: Concatenation of integer at i'th and j'th index have even number of digits (Even digit Concatenation)Sum of digits in the first half = sum of digits in the second half (Balanced Digit Sum)The task is to count all such valid pairs in the given array wi
9 min read
Arrange array elements such that last digit of an element is equal to first digit of the next element
Given an array arr[] of integers, the task is to arrange the array elements such that the last digit of an element is equal to first digit of the next element. Examples: Input: arr[] = {123, 321} Output: 123 321 Input: arr[] = {451, 378, 123, 1254} Output: 1254 451 123 378 Naive approach: Find all the permutations of the array elements and then pri
9 min read
Print all n digit patterns formed by mobile Keypad
Given a number n. we need to print all N digit patterns formed by mobile Keypad. Note: we can move up, down, left, right from any key of mobile keypad, and every pattern contains the unique key. Examples: Input : N = 3 Output : all 3 digit Pattern are : 123, 125, 145, 147 236, 214, 258, 256, 254 321, 325, 369, 365 412, 456, 452, 458, 478 and so on
11 min read
Number of N digit integers with weight W
Given N, the number of digits of an integer which is greater than or equal to 2 and a weight W. The task is to find the count of integers that have N digits and weight W.Note: Weight is defined as the difference between the consecutive digits of an integer. Examples: Input : N = 2, W = 3 Output : 6 Input : N = 2, W = 4 Output : 5 In the above examp
7 min read
Smallest integer with digit sum M and multiple of N
Given two positive integers N and M, the task is to find the smallest positive integer which is divisible by N and whose digit sum is M. Print -1 if no such integer exists within the range of int. Examples: Input: N = 13, M = 32 Output: 8879 8879 is divisible by 13 and its Sum of digits of 8879 is 8+8+7+9 = 32 i.e. equals to M Input: N = 8, M = 32;
5 min read
Print digit's position to be removed to make a number divisible by 6
Given a number N, remove exactly one digit to make the number divisible by 6 (make it the largest possible). Print the position that has to be removed, If not possible then print -1. Examples: Input: 123 Output: 3 Explanation: Remove 3rd position element and hence the number is 12, which is divisible by 6 and is the greatest possible. Input: 134 Ou
15 min read
Check input character is alphabet, digit or special character
All characters whether alphabet, digit or special character have ASCII value. Input character from the user will determine if it's Alphabet, Number or Special character.ASCII value ranges- For capital alphabets 65 - 90For small alphabets 97 - 122For digits 48 - 57 Examples : Input : 8 Output : Digit Input : E Output : Alphabet C/C++ Code // CPP pro
3 min read
Number of n digit stepping numbers
Given n, find count of n digit Stepping numbers. A number is called stepping number if all adjacent digits have an absolute difference of 1. 321 is a Stepping Number while 421 is not. Examples : Input : 2 Output : 17 Explanation: The numbers are 10, 12, 21, 23, 32, 34, 43, 45, 54, 56, 65, 67, 76, 78, 87, 89, 98. Input : 1 Output : 10 Explanation: t
13 min read
Count numbers with unit digit k in given range
Here given a range from low to high and given a number k.You have to find out the number of count which a number has same digit as kExamples: Input: low = 2, high = 35, k = 2 Output: 4 Numbers are 2, 12, 22, 32 Input: low = 3, high = 30, k = 3 Output: 3 Numbers are 3, 13, 23 A naive approach is to traverse through all numbers in given range and che
7 min read