Count all possible texts that can be formed from Number using given mapping
Last Updated :
23 Jul, 2025
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>
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));
}
}
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem