All combinations of strings that can be used to dial a number
Last Updated :
13 Aug, 2024
Given a number, print all possible combinations of strings that can be used to dial the given number in a phone with following specifications. In the given phone, we can dial, 2 using A or B or C, 3 using D or E or F, ................... 8 using T or U or V, 9 using W or X or Y or Z, 1 using only 1 0 using 0. For example if 23, is the given phone number, the program should print AD, AE, AF, BD, BE, BF, CD, CE, CF
The idea is to store digit to characters mapping in hash map. The map stores all characters that can be used dial a digit. We place every possible character for current digit and recur for remaining digits.
Algorithm:
- Create a hash map with keys as digits from 0 to 9 and values as the set of characters associated with each digit.
- Define a recursive function printStrings that takes four arguments:
a. phNo - the input phone number
b. i - the index of the current digit being processed
c. hm - the hash map of digit to character sets
d. str - the string of characters generated so far - Inside the printStrings function:
a. Check if i has reached the end of the phone number. If yes, print the generated string and return.
b. Get the set of characters associated with the current digit from the hash map.
c. Iterate over each character in the set and:
i. Append the character to the string str.
ii. Recursively call the printStrings function for the next digit.
iii. Remove the last character from the string str. - Define a function printStringForNumber that takes one argument:
a. phNo - the input phone number - Inside the printStringForNumber function, call the printStrings function with the arguments phNo, 0, hm, and an empty string.
Below is Java implementation of this idea.
Implementation:
C++
// C++ program for the above approach
#include <iostream>
#include <unordered_map>
using namespace std;
void printStrings(string phNo, int i,
unordered_map<char, string> hm,
string str)
{
if (i == phNo.length())
{
cout << str << " ";
return;
}
string s = hm[phNo[i]];
for (int j = 0; j < s.length(); j++)
{
str.push_back(s[j]);
printStrings(phNo, i+1, hm, str);
str.pop_back();
}
}
void printStringForNumber(string phNo)
{
unordered_map<char, string> hm = {
{'2', "ABC"},
{'3', "DEF"},
{'4', "GHI"},
{'5', "JKL"},
{'6', "MNO"},
{'7', "PQRS"},
{'8', "TUV"},
{'9', "WXYZ"},
{'1', "1"},
{'0', "0"}
};
string str;
printStrings(phNo, 0, hm, str);
}
int main()
{
printStringForNumber("23");
return 0;
}
// This code is contributed by codebraxnzt
Java
// Java program to print all possible key strings
// that can be used to dial a phone number.
import java.util.HashMap;
class ConvertToString
{
// A Recursive function to print all combinations
// that can be used to dial a given number.
// phNo ==> Given Phone Number
// i ==> Current digit of phNo to be processed
// hm ==> Stores characters that can be used to
// to dial a digit.
// str ==> Current output string
static void printStrings(String phNo, int i,
HashMap<Character, String> hm,
StringBuilder str)
{
// If all digits are processed, print output
// string
if (i == phNo.length())
{
System.out.print(str + " ");
return;
}
// Get current digit of phNo, and recur for all
// characters that can be used to dial it.
String s = hm.get(phNo.charAt(i));
for (int j = 0; j < s.length(); j++)
{
str.append(s.charAt(j));
printStrings(phNo, i+1, hm, str);
str.deleteCharAt(str.length()-1);
}
}
// Prints all possible combinations of strings that
// can be used to dial c[].
static void printStringForNumber(String phNo)
{
// Create a HashMap
HashMap<Character, String> hm =
new HashMap<Character, String>();
// For every digit, store characters that can
// be used to dial it.
hm.put('2', "ABC");
hm.put('3', "DEF");
hm.put('4', "GHI");
hm.put('5', "JKL");
hm.put('6', "MNO");
hm.put('7', "PQRS");
hm.put('8', "TUV");
hm.put('9', "WXYZ");
hm.put('1', "1");
hm.put('0', "0");
// Create a string to store a particular output
// string
StringBuilder str = new StringBuilder();
// Call recursive function
printStrings(phNo, 0, hm, str);
}
// Driver code to test above methods
public static void main(String args[])
{
// Prints
printStringForNumber("23");
}
}
Python
def print_strings(ph_no, i, hm, s):
if i == len(ph_no):
print(s, end=" ")
return
for c in hm[ph_no[i]]:
print_strings(ph_no, i+1, hm, s+c)
def print_string_for_number(ph_no):
hm = {
'2': "ABC",
'3': "DEF",
'4': "GHI",
'5': "JKL",
'6': "MNO",
'7': "PQRS",
'8': "TUV",
'9': "WXYZ",
'1': "1",
'0': "0"
}
s = ""
print_strings(ph_no, 0, hm, s)
print_string_for_number("23")
C#
using System;
using System.Collections.Generic;
class Program {
static void printStrings(string phNo, int i,
Dictionary<char, string> hm,
string str)
{
if (i == phNo.Length)
{
Console.Write(str + " ");
return;
}
string s = hm[phNo[i]];
for (int j = 0; j < s.Length; j++)
{
str += s[j];
printStrings(phNo, i+1, hm, str);
str = str.Remove(str.Length-1);
}
}
static void printStringForNumber(string phNo)
{
Dictionary<char, string> hm = new Dictionary<char, string>
{
{'2', "ABC"},
{'3', "DEF"},
{'4', "GHI"},
{'5', "JKL"},
{'6', "MNO"},
{'7', "PQRS"},
{'8', "TUV"},
{'9', "WXYZ"},
{'1', "1"},
{'0', "0"}
};
string str = "";
printStrings(phNo, 0, hm, str);
}
static void Main(string[] args) {
printStringForNumber("23");
}
}
JavaScript
function printStrings(phNo, i, hm, s) {
if (i === phNo.length) {
console.log(s + " ");
return;
}
for (let j = 0; j < hm[phNo[i]].length; j++) {
s += hm[phNo[i]][j];
printStrings(phNo, i+1, hm, s);
s = s.slice(0, -1);
}
}
function printStringForNumber(phNo) {
let hm = {
'2': "ABC",
'3': "DEF",
'4': "GHI",
'5': "JKL",
'6': "MNO",
'7': "PQRS",
'8': "TUV",
'9': "WXYZ",
'1': "1",
'0': "0"
};
let s = "";
printStrings(phNo, 0, hm, s);
}
printStringForNumber("23");
OutputAD AE AF BD BE BF CD CE CF
Time Complexity : O(2^n), here n is length of string
Auxiliary Space : O(n)
Similar Reads
Combinations in a String of Digits Given an input string of numbers, find all combinations of numbers that can be formed using digits in the same order.Examples: Input : 123 Output :1 2 3 1 23 12 3 123Input : 1234Output : 1 2 3 4 1 2 34 1 23 4 1 234 12 3 4 12 34 123 4 1234 The problem can be solved using recursion. We keep track of t
10 min read
Alphanumeric Abbreviations of a String Given a string of characters of length less than 10. We need to print all the alpha-numeric abbreviation of the string. The alpha-numeric abbreviation is in the form of characters mixed with the digits which is equal to the number of skipped characters of a selected substring. So, whenever a substri
11 min read
Convert given string to a valid mobile number Given a string M consisting of letters, digits and symbols, the task is to convert the string to a valid mobile number by removing all characters except the digits in the following format: Form a substring of 3 digits while the length of the remaining string is greater than 3.Enclose each substring
7 min read
Count all possible texts that can be formed from Number using given mapping 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'.
15+ min read
Applications, Advantages and Disadvantages of String The String data structure is the backbone of programming languages and the building blocks of communication. String data structures are one of the most fundamental and widely used tools in computer science and programming. They allow for the representation and manipulation of text and character sequ
6 min read