VOOZH about

URL: https://www.geeksforgeeks.org/dsa/combinations-strings-can-used-dial-given-phone-number/

⇱ All combinations of strings that can be used to dial a number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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:


Output
AD AE AF BD BE BF CD CE CF 

Time Complexity : O(2^n),  here n is length of string 

Auxiliary Space : O(n)

Comment
Article Tags:
Article Tags: