Java ArrayList to print all possible words from phone digits

Given a keypad of a mobile, and keys that need to be pressed, the task is to print all the words which are possible to generate by pressing these numbers.


{ 1 }     { 2 }     { 3 }
[ABC]     [DEF]     [GHI]

{ 4 }     { 5 }    { 6 }
[JKL]     [MNO]    [PQR]

{ 7 }     { 8 }    { 9 }
[STU]     [VWX]    [YZ]

Examples:

Input: str = "12" 
Output: [ad, bd, cd, ae, be, ce, af, bf, cf]

Input: str = "4"
Output: [j, k, l]


We have discussed one approach in Print all possible words from phone digits

In this post, we have discussed another approach. We write a recursive function that generates all the words that can be generated with the given keys. Terminating condition is be when the passed string is empty, in that case the function will return an empty ArrayList.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
import java.util.ArrayList;
  
public class GFG {
  
    // String array to store keypad characters
    static final String codes[]
        = { " ", "abc", "def",
            "ghi", "jkl", "mno",
            "pqr", "stu", "vwx",
            "yz" };
  
    // Function that returns an Arraylist
    // which contains all the generated words
    public static ArrayList<String> printKeyWords(String str)
    {
  
        // If str is empty
        if (str.length() == 0) {
            ArrayList<String> baseRes = new ArrayList<>();
            baseRes.add("");
  
            // Return an Arraylist containing
            // empty string
            return baseRes;
        }
  
        // First character of str
        char ch = str.charAt(0);
  
        // Rest of the characters of str
        String restStr = str.substring(1);
  
        ArrayList<String> prevRes = printKeyWords(restStr);
        ArrayList<String> Res = new ArrayList<>();
  
        String code = codes[ch - '0'];
  
        for (String val : prevRes) {
  
            for (int i = 0; i < code.length(); i++) {
                Res.add(code.charAt(i) + val);
            }
        }
        return Res;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String str = "23";
  
        // Print all the possible words
        System.out.println(printKeyWords(str));
    }
}

chevron_right


Output:

[dg, eg, fg, dh, eh, fh, di, ei, fi]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.