Open In App

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

Last Updated : 28 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 1: 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.

Efficient approach 2: Using DP Tabulation method ( Iterative approach )

DP tabulation is better than Dp + memorization because memoization method needs extra stack space because of recursion calls.

Steps to solve this problem : 

  • Create a table to store the solution of the subproblems.
  • Initialize the table with base cases
  • Fill up the table iteratively
  • Return the final solution

C++

// C++ code to implement above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// function to calculate number of possibilities
long countPossibilities(string s)
{
    int n = s.length();
    vector<long> dp(n + 1);
 
    // Base case: empty string has only
      // one possibility as there is only one way
    // to express empty text.
    dp[n] = 1;
 
    // Fill the DP table in reverse order
    for (int i = n - 1; i >= 0; i--) {
        int ans = 0;
 
        // If the current element is same as next
        // then add dp[i+2] to ans
        if (i + 1 < n && s[i] == s[i + 1]) {
            ans += dp[i + 2];
 
            // If s[i]==s[i+2] then add dp[i+3] to ans
            if (i + 2 < n && s[i] == s[i + 2]) {
                ans += dp[i + 3];
 
                // If s[i] is '8' and s[i]==s[i+3]
                // then add dp[i+4] to ans
                if (i + 3 < n && s[i] == '8'
                    && s[i] == s[i + 3]) {
                    ans += dp[i + 4];
                }
            }
        }
 
        // Add dp[i+1] to ans
        ans += dp[i + 1];
 
        // Store ans in dp[i]
        dp[i] = ans;
    }
 
    // Return the final answer
    return dp[0];
}
 
// Driver code
int main()
{
    string s = "88881";
 
    // Function call
    cout << countPossibilities(s);
    return 0;
}
// this code is contributed by bhardwajji

                    

Java

import java.util.*;
 
public class Main
{
   
// function to calculate number of possibilities
static long countPossibilities(String s) {
int n = s.length();
long[] dp = new long[n + 1];
 
 
    // Base case: empty string has only
    // one possibility as there is only one way
    // to express empty text.
    dp[n] = 1;
 
    // Fill the DP table in reverse order
    for (int i = n - 1; i >= 0; i--) {
        int ans = 0;
 
        // If the current element is same as next
        // then add dp[i+2] to ans
        if (i + 1 < n && s.charAt(i) == s.charAt(i + 1)) {
            ans += dp[i + 2];
 
            // If s[i]==s[i+2] then add dp[i+3] to ans
            if (i + 2 < n && s.charAt(i) == s.charAt(i + 2)) {
                ans += dp[i + 3];
 
                // If s[i] is '8' and s[i]==s[i+3]
                // then add dp[i+4] to ans
                if (i + 3 < n && s.charAt(i) == '8' && s.charAt(i) == s.charAt(i + 3)) {
                    ans += dp[i + 4];
                }
            }
        }
 
        // Add dp[i+1] to ans
        ans += dp[i + 1];
 
        // Store ans in dp[i]
        dp[i] = ans;
    }
 
    // Return the final answer
    return dp[0];
}
 
// Driver code
public static void main(String[] args) {
    String s = "88881";
 
    // Function call
    System.out.println(countPossibilities(s));
}
}

                    

Python3

# Python 3 code to implement above approach
 
def countPossibilities(s):
    n = len(s)
    dp = [0] * (n + 1)
 
    # Base case: empty string has only one possibility as there is only one way
    # to express empty text.
    dp[n] = 1
 
    # Fill the DP table in reverse order
    for i in range(n - 1, -1, -1):
        ans = 0
 
        # If the current element is same as next
        # then add dp[i+2] to ans
        if i + 1 < n and s[i] == s[i + 1]:
            ans += dp[i + 2]
 
            # If s[i]==s[i+2] then add dp[i+3] to ans
            if i + 2 < n and s[i] == s[i + 2]:
                ans += dp[i + 3]
 
                # If s[i] is '8' and s[i]==s[i+3]
                # then add dp[i+4] to ans
                if i + 3 < n and s[i] == '8' and s[i] == s[i + 3]:
                    ans += dp[i + 4]
 
        # Add dp[i+1] to ans
        ans += dp[i + 1]
 
        # Store ans in dp[i]
        dp[i] = ans
 
    # Return the final answer
    return dp[0]
 
# Driver code
s = "88881"
 
# Function call
print(countPossibilities(s))

                    

Javascript

// JavaScript Program for the above approach
 
function countPossibilities(s) {
  let n = s.length;
  let dp = new Array(n + 1).fill(0);
 
  // Base case: empty string has only one possibility as there is only one way
  // to express empty text.
  dp[n] = 1;
 
  // Fill the DP table in reverse order
  for (let i = n - 1; i >= 0; i--) {
    let ans = 0;
 
    // If the current element is same as next
    // then add dp[i+2] to ans
    if (i + 1 < n && s[i] == s[i + 1]) {
      ans += dp[i + 2];
 
      // If s[i]==s[i+2] then add dp[i+3] to ans
      if (i + 2 < n && s[i] == s[i + 2]) {
        ans += dp[i + 3];
 
        // If s[i] is '8' and s[i]==s[i+3]
        // then add dp[i+4] to ans
        if (i + 3 < n && s[i] == '8' && s[i] == s[i + 3]) {
          ans += dp[i + 4];
        }
      }
    }
 
    // Add dp[i+1] to ans
    ans += dp[i + 1];
 
    // Store ans in dp[i]
    dp[i] = ans;
  }
 
  // Return the final answer
  return dp[0];
}
 
// Driver code
let s = "88881";
 
// Function call
console.log(countPossibilities(s));
 
 
// This code is contributed by codebraxnzt

                    

C#

// C# code to implement above approach
 
using System;
 
public class GFG {
    // function to calculate number of possibilities
    public static long CountPossibilities(string s) {
        int n = s.Length;
        long[] dp = new long[n + 1];
 
        // Base case: empty string has only
        // one possibility as there is only one way
        // to express empty text.
        dp[n] = 1;
 
        // Fill the DP table in reverse order
        for (int i = n - 1; i >= 0; i--) {
            long ans = 0;
 
            // If the current element is same as next
            // then add dp[i+2] to ans
            if (i + 1 < n && s[i] == s[i + 1]) {
                ans += dp[i + 2];
 
                // If s[i]==s[i+2] then add dp[i+3] to ans
                if (i + 2 < n && s[i] == s[i + 2]) {
                    ans += dp[i + 3];
 
                    // If s[i] is '8' and s[i]==s[i+3]
                    // then add dp[i+4] to ans
                    if (i + 3 < n && s[i] == '8'
                        && s[i] == s[i + 3]) {
                        ans += dp[i + 4];
                    }
                }
            }
 
            // Add dp[i+1] to ans
            ans += dp[i + 1];
 
            // Store ans in dp[i]
            dp[i] = ans;
        }
 
        // Return the final answer
        return dp[0];
    }
 
    // Driver code
    public static void Main() {
          // Input string
        string s = "88881";
 
        // Function call
        Console.WriteLine(CountPossibilities(s));
    }
}

                    

Output
8

Time Complexity: O(N)

Auxiliary Space: O(N)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads