Skip to content
Related Articles

Related Articles

Count all possible texts that can be formed from Number using given mapping

View Discussion
Improve Article
Save Article
  • Last Updated : 20 Jul, 2022
View Discussion
Improve Article
Save Article

Given a number N and a mapping of letters to each integer from 1 to 8, which are: 
{1: ‘abc’, 2: ‘def’, 3: ‘ghi’, 4: ‘jkl’, 5: ‘mno’, 6: ‘pqr’, 7: ‘stu’, 8: ‘wxyz’}
The mapping denotes that a single 1 can be replaced by ‘a’, a pair of 1 can be replaced by ‘b’ and a triplet of 1 can be replaced by ‘c’. Similarly for all other digits. The task is to find the total possible number of texts formed by replacing the digits of the given N.

Examples: 

Input: N = 22233
Output: 8
Explanation:  All the possible texts are dddgg, dddh, edgg, edh, degg, deh, fgg, fh.
So the total number texts that can be interpreted is 8.

Input: N = 88881
Output: 8

 

Naive Approach: The approach is to generate all possible combinations using recursion and count the total possible texts.

Time Complexity: O(2D) where D is the total number of digits in the N
Auxiliary Space: O(1)

Efficient Approach: This problem can be solved using dynamic programming using the following idea:

At a time the number of occurrences which can be considered for each digit is 1, 2 or 3 (4 occurrences only for digit 8). 

Consider the number of ways to form a string using the digits after ith position from left is denoted as f(i).
Therefore, from the above observation it can be said that:
f(i) = f(i+1) + f(i+2) + f(i+3) [+f(i+4) if the digit is 8]. because continuous one, two, or three occurrences of a number can be expressed using a single letter.

It can be seen that If Ni ≠ Ni+1 then f(i) = f(i+1)
If Ni = Ni+1 then the equation holds only till the 2nd term i.e f(i) = f(i+1) + f(i+2).
Similarly for other cases like Ni = Ni + 1 = Ni + 2 and all.

So it can be said that f(i) = j = 1 to m∑ f(i + j) where m is the number of continuous occurrences of Ni and m does not exceed 3 (4 when the digit is ‘8’).

Follow the steps mentioned below to implement the idea:

  • Declare a dp[] array of size string(s) length and initialize it to -1 to store the values calculated till now.
  • Use a recursive function to implement the above functional relations and call from 0th index.
    • If the current index is out of string then return 1
    • If the value for the current index is already calculated (i.e, dp[] value is not -1) then return the value stored in dp[].
    • Now check the index till which there is a continuous occurrence of the current digit and calculate the value of the above function accordingly.
    • Call the recursive function for the next index and continue the process.
    • Store the answer for the current index (say i) in dp[i] and return the same to the previous call.
  • The value returned for the first index is the required total number of ways.

Below is the implementation of the above approach:

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Recursive function to calculate
// the number of possible ways
long countPossibilities(string s, int idx,
                        vector<long>& dp)
{
    // If current index is out of the string
    // then return 1 as there is only one way
    // to express empty text.
    if (idx > s.length())
        return 1;
 
    // If the value of the dp is already filled
    // then return it
    if (dp[idx] != -1)
        return dp[idx];
 
    // Declare ans
    int ans = 0;
 
    // If the current element is same as next
    // then recur function from idx+2 index
    // and store its value in ans
    if (idx + 1 < s.length() && s[idx] == s[idx + 1]) {
        ans = ans + countPossibilities(s, idx + 2,
                                       dp);
 
        // If s[idx]==s[idx+2] then recur from
        // idx+3 index and store its value in ans
        if (idx + 2 < s.length() && s[idx] == s[idx + 2]) {
            ans = ans + countPossibilities(s,
                                           idx + 3, dp);
 
            // If s[idx] is '8'(as 8 has
            // 4 characters mapped in it) and
            // s[idx]==s[idx+3] then recur from
            // idx+4 and store it in ans
            if (idx + 3 < s.length() && (s[idx] == '8')
                && s[idx] == s[idx + 3]) {
                ans += countPossibilities(s, idx + 4,
                                          dp);
            }
        }
    }
 
    // Recur for next index in order
    // to find out all the possibilities
    ans += countPossibilities(s, idx + 1, dp);
 
    // Store ans in dp
    dp[idx] = ans;
 
    // Return the value to previous function call
    return dp[idx];
}
 
// Driver code
int main()
{
    string s = "88881";
    vector<long> dp(s.length() + 1, -1);
 
    // Function call
    cout << countPossibilities(s, 0, dp);
    return 0;
}


Java




// JAVA code to implement the approach
import java.util.*;
class GFG {
 
  // Recursive function to calculate
  // the number of possible ways
  public static int countPossibilities(String s, int idx,
                                       int dp[])
  {
 
    // If current index is out of the string
    // then return 1 as there is only one way
    // to express empty text.
    if (idx > s.length())
      return 1;
 
    // If the value of the dp is already filled
    // then return it
    if (dp[idx] != -1)
      return dp[idx];
 
    // Declare ans
    int ans = 0;
 
    // If the current element is same as next
    // then recur function from idx+2 index
    // and store its value in ans
    if (idx + 1 < s.length()
        && s.charAt(idx) == s.charAt(idx + 1)) {
      ans = ans + countPossibilities(s, idx + 2, dp);
 
      // If s[idx]==s[idx+2] then recur from
      // idx+3 index and store its value in ans
      if (idx + 2 < s.length()
          && s.charAt(idx) == s.charAt(idx + 2)) {
        ans = ans
          + countPossibilities(s, idx + 3, dp);
 
        // If s[idx] is '8'(as 8 has
        // 4 characters mapped in it) and
        // s[idx]==s[idx+3] then recur from
        // idx+4 and store it in ans
        if (idx + 3 < s.length()
            && (s.charAt(idx) == '8')
            && s.charAt(idx) == s.charAt(idx + 3)) {
          ans += countPossibilities(s, idx + 4,
                                    dp);
        }
      }
    }
 
    // Recur for next index in order
    // to find out all the possibilities
    ans += countPossibilities(s, idx + 1, dp);
 
    // Store ans in dp
    dp[idx] = ans;
 
    // Return the value to previous function call
    return dp[idx];
  }
 
  // Driver code
  public static void main(String[] args)
  {
    String s = "88881";
    int dp[] = new int[s.length() + 1];
    Arrays.fill(dp, -1);
 
    // Function call
    System.out.print(countPossibilities(s, 0, dp));
  }
}
 
// This code is contributed by Taranpreet


Python3




# Python3 code to implement the approach
 
# Recursive function to calculate
# the number of possible ways
def countPossibilities(s, idx, dp) :
 
    # If current index is out of the string
    # then return 1 as there is only one way
    # to express empty text.
    if (idx > len(s)) :
        return 1;
 
    # If the value of the dp is already filled
    # then return it
    if (dp[idx] != -1) :
        return dp[idx];
 
    # Declare ans
    ans = 0;
 
    # If the current element is same as next
    # then recur function from idx+2 index
    # and store its value in ans
    if (idx + 1 < len(s) and s[idx] == s[idx + 1]) :
        ans = ans + countPossibilities(s, idx + 2, dp);
 
        # If s[idx]==s[idx+2] then recur from
        # idx+3 index and store its value in ans
        if (idx + 2 < len(s) and s[idx] == s[idx + 2]) :
            ans = ans + countPossibilities(s,idx + 3, dp);
 
            # If s[idx] is '8'(as 8 has
            # 4 characters mapped in it) and
            # s[idx]==s[idx+3] then recur from
            # idx+4 and store it in ans
            if (idx + 3 < len(s) and (s[idx] == '8') and s[idx] == s[idx + 3]) :
                ans += countPossibilities(s, idx + 4,dp);
 
    # Recur for next index in order
    # to find out all the possibilities
    ans += countPossibilities(s, idx + 1, dp);
 
    # Store ans in dp
    dp[idx] = ans;
 
    # Return the value to previous function call
    return dp[idx];
 
# Driver code
if __name__ == "__main__" :
 
    s = "88881";
    dp = [-1]*(len(s) + 1)
 
    # Function call
    print(countPossibilities(s, 0, dp));
 
    # This code is contributed by AnkThon


C#




// C# code to implement the approach
using System;
using System.Collections;
class GFG {
 
  // Recursive function to calculate
  // the number of possible ways
  public static int countPossibilities(String s, int idx,
                                       int[] dp)
  {
 
    // If current index is out of the string
    // then return 1 as there is only one way
    // to express empty text.
    if (idx > s.Length)
      return 1;
 
    // If the value of the dp is already filled
    // then return it
    if (dp[idx] != -1)
      return dp[idx];
 
    // Declare ans
    int ans = 0;
 
    // If the current element is same as next
    // then recur function from idx+2 index
    // and store its value in ans
    if (idx + 1 < s.Length
        && s[idx] == s[idx + 1]) {
      ans = ans + countPossibilities(s, idx + 2, dp);
 
      // If s[idx]==s[idx+2] then recur from
      // idx+3 index and store its value in ans
      if (idx + 2 < s.Length
          && s[idx] == s[idx + 2]) {
        ans = ans
          + countPossibilities(s, idx + 3, dp);
 
        // If s[idx] is '8'(as 8 has
        // 4 characters mapped in it) and
        // s[idx]==s[idx+3] then recur from
        // idx+4 and store it in ans
        if (idx + 3 < s.Length
            && (s[idx] == '8')
            && s[idx] == s[idx + 3]) {
          ans += countPossibilities(s, idx + 4,
                                    dp);
        }
      }
    }
 
    // Recur for next index in order
    // to find out all the possibilities
    ans += countPossibilities(s, idx + 1, dp);
 
    // Store ans in dp
    dp[idx] = ans;
 
    // Return the value to previous function call
    return dp[idx];
  }
 
  // Driver code
  public static void Main()
  {
    String s = "88881";
    int[] dp = new int[s.Length + 1];
    Array.Fill(dp, -1);
 
    // Function call
    Console.Write(countPossibilities(s, 0, dp));
  }
}
 
// This code is contributed by Saurabh Jaiswal


Javascript




<script>
  // Recursive function to calculate
  // the number of possible ways
 function countPossibilities(s, idx, dp)
  {
    let res=1;
    // If current index is out of the string
    // then return 1 as there is only one way
    // to express empty text.
    if (idx > s.length)
      return 1;
 
    // If the value of the dp is already filled
    // then return it
    if (dp[idx] !== -1)
      return dp[idx];
 
    // Declare ans
    let ans = 0;
 
    // If the current element is same as next
    // then recur function from idx+2 index
    // and store its value in ans
    if ((idx + 1) < s.length && s.charAt(idx) == s.charAt(idx + 1)) {
        let a=countPossibilities(s, idx + 2, dp);
      ans = ans + a;
 
      // If s[idx]==s[idx+2] then recur from
      // idx+3 index and store its value in ans
      if (idx + 2 < s.length
          && s.charAt(idx) == s.charAt(idx + 2)) {
              let b = countPossibilities(s, idx + 3, dp);
        ans = ans
          + b;
 
        // If s[idx] is '8'(as 8 has
        // 4 characters mapped in it) and
        // s[idx]==s[idx+3] then recur from
        // idx+4 and store it in ans
        if (idx + 3 < s.length
            && (s.charAt(idx) == '8')
            && s.charAt(idx) == s.charAt(idx + 3)) {
                let c = countPossibilities(s, idx + 4,
                                    dp);
          ans += c;
        }
      }
    }
 
    // Recur for next index in order
    // to find out all the possibilities
    let d = countPossibilities(s, idx + 1, dp);
    ans += d;
 
    // Store ans in dp
    dp[idx] = ans;
 
    // Return the value to previous function call
    return dp[idx];
  }
 
  // Driver code
    let s = "88881";
    const dp =[];
    for(let i=0;i<(s.length+1);i++)
    {
        dp[i]=-1;
    }
 
    // Function call
   let ans = countPossibilities(s, 0, dp);
    console.log(ans);
     
    // This code is contributed by akashish_.
</script>


Output

8

Time Complexity:  O(N)
Auxiliary Space: O(N), since N extra space has been taken.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!