Open In App

Print all possible words from phone digits

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a keypad represented by an integer array arr[] containing digits from [0, 9], the task is to print all possible letter combinations that the numbers could represent. A mapping of digits to letters (just like on the telephone buttons) is being followed.
Note: 0 and 1 do not map to any letters.

Mobile-keypad

Examples:

Input: arr[] = [2, 3]
Output: [ad, ae, af, bd, be, bf, cd, ce, cf]

Input: arr[] = [2]
Output: [a, b, c]

[Approach 1] Using Recursion and Backtracking - O(4^n) Time and O(n) Space

The idea is to use recursion to generate all possible letter combinations for the given digits. Each digit maps to a set of letters, and the recursion builds combinations by appending letters for the current digit to a growing string (prefix). The base case is reached when the prefix length matches the size of the input array, at which point the combination is added to the result. If a digit is invalid (not in the range 2-9), it is skipped.

C++
// C++ implementation to print all possible
// letter combinations using recursion
#include <iostream>
#include <vector>
using namespace std;

// Recursive function to generate combinations
void possibleWordsRec(vector<int> &arr, int index, string &prefix, 
                      vector<string> &padMap, vector<string> &res) {

    // Base case: if the prefix length matches arr size
    if (index == arr.size()) {
        res.push_back(prefix);
        return;
    }

    // Get the corresponding digit
    int digit = arr[index];

    // Skip invalid digits
    if (digit < 2 || digit > 9) {
        possibleWordsRec(arr, index + 1, prefix, padMap, res);
        return;
    }

    // Place all possible letters for this digit
    for (char ch : padMap[digit]) {
        prefix.push_back(ch);
        possibleWordsRec(arr, index + 1, prefix, padMap, res);
        prefix.pop_back();
    }
}

// Function to find all possible letter combinations
vector<string> possibleWords(vector<int> &arr) {
    vector<string> res;
    vector<string> padMap = {"", "", "abc", "def", "ghi", "jkl",
                             		"mno", "pqrs", "tuv", "wxyz"};
    string prefix = "";

    possibleWordsRec(arr, 0, prefix, padMap, res);
    return res;
}

int main() {
    vector<int> arr = {2, 3};
    vector<string> words = possibleWords(arr);
  
    for (string word : words)
        cout << word << " ";
    return 0;
}
Java
// Java implementation to print all possible
// letter combinations using recursion
import java.util.ArrayList;

class GfG {
  
    // Recursive function to generate combinations
    static void possibleWordsRec(int[] arr, int index, StringBuilder prefix, 
                                         String[] padMap, ArrayList<String> res) {
        // Base case: if the prefix length matches arr size
        if (index == arr.length) {
            res.add(prefix.toString());
            return;
        }

        // Get the corresponding digit
        int digit = arr[index];

        // Skip invalid digits
        if (digit < 2 || digit > 9) {
            possibleWordsRec(arr, index + 1, prefix, padMap, res);
            return;
        }

        // Place all possible letters for this digit
        for (char ch : padMap[digit].toCharArray()) {
            prefix.append(ch);
            possibleWordsRec(arr, index + 1, prefix, padMap, res);
            prefix.deleteCharAt(prefix.length() - 1);
        }
    }

    // Function to find all possible letter combinations
    static ArrayList<String> possibleWords(int[] arr) {
        ArrayList<String> res = new ArrayList<>();
        String[] padMap = {"", "", "abc", "def", "ghi", "jkl",
                           "mno", "pqrs", "tuv", "wxyz"};
      
        StringBuilder prefix = new StringBuilder();

        possibleWordsRec(arr, 0, prefix, padMap, res);
        return res;
    }

    public static void main(String[] args) {
        int[] arr = {2, 3};
        ArrayList<String> words = possibleWords(arr);

        for (String word : words)
            System.out.print(word + " ");
    }
}
Python
# Python implementation to print all possible
# letter combinations using recursion

# Recursive function to generate combinations
def possibleWordsRec(arr, index, prefix, padMap, res):
    # Base case: if the prefix length matches arr size
    if index == len(arr):
        res.append(prefix)
        return

    # Get the corresponding digit
    digit = arr[index]

    # Skip invalid digits
    if digit < 2 or digit > 9:
        possibleWordsRec(arr, index + 1, prefix, padMap, res)
        return

    # Place all possible letters for this digit
    for ch in padMap[digit]:
        possibleWordsRec(arr, index + 1, prefix + ch, padMap, res)

# Function to find all possible letter combinations
def possibleWords(arr):
    res = []
    padMap = ["", "", "abc", "def", "ghi", "jkl", 
              "mno", "pqrs", "tuv", "wxyz"]
    possibleWordsRec(arr, 0, "", padMap, res)
    return res

if __name__ == "__main__":
    arr = [2, 3]
    words = possibleWords(arr)

    for word in words:
        print(word, end=" ")
C#
// C# implementation to print all possible
// letter combinations using recursion
using System;
using System.Collections.Generic;

class GfG {
  
    // Recursive function to generate combinations
    static void possibleWordsRec(int[] arr, int index, string prefix, 
                                  string[] padMap, List<string> res) {
        // Base case: if the prefix length matches arr size
        if (index == arr.Length) {
            res.Add(prefix);
            return;
        }

        // Get the corresponding digit
        int digit = arr[index];

        // Skip invalid digits
        if (digit < 2 || digit > 9) {
            possibleWordsRec(arr, index + 1, prefix, padMap, res);
            return;
        }

        // Place all possible letters for this digit
        foreach (char ch in padMap[digit]) {
            possibleWordsRec(arr, index + 1, prefix + ch, padMap, res);
        }
    }

    // Function to find all possible letter combinations
    static List<string> possibleWords(int[] arr) {
        List<string> res = new List<string>();
        string[] padMap = { "", "", "abc", "def", "ghi", "jkl",
                            "mno", "pqrs", "tuv", "wxyz" };
        possibleWordsRec(arr, 0, "", padMap, res);
        return res;
    }

    static void Main(string[] args) {
        int[] arr = { 2, 3 };
        List<string> words = possibleWords(arr);

        foreach (string word in words)
            Console.Write(word + " ");
    }
}
JavaScript
// JavaScript implementation to print all possible
// letter combinations using recursion

// Recursive function to generate combinations
function possibleWordsRec(arr, index, prefix, padMap, res) {

    // Base case: if the prefix length matches arr size
    if (index === arr.length) {
        res.push(prefix);
        return;
    }

    // Get the corresponding digit
    const digit = arr[index];

    // Skip invalid digits
    if (digit < 2 || digit > 9) {
        possibleWordsRec(arr, index + 1, prefix, padMap, res);
        return;
    }

    // Place all possible letters for this digit
    for (let ch of padMap[digit]) {
        possibleWordsRec(arr, index + 1, prefix + ch, padMap, res);
    }
}

// Function to find all possible letter combinations
function possibleWords(arr) {
    const res = [];
    const padMap = ["", "", "abc", "def", "ghi", "jkl", 
                    "mno", "pqrs", "tuv", "wxyz"];
    possibleWordsRec(arr, 0, "", padMap, res);
    return res;
}

// Driver Code
const arr = [2, 3];
const words = possibleWords(arr);

console.log(words.join(" "));

Output
ad ae af bd be bf cd ce cf 

[Approach 2] Using Queue - O(4^n) Time and O(4^n) Space

The idea is to use a queue to iteratively generate all possible letter combinations for the given digits. Starting with an empty string in the queue, we repeatedly extend the current string by appending all possible letters corresponding to the next digit. If the string length matches the size of the input array, it is added to the result. This approach ensures all combinations are generated systematically. For implementation of this approach go to this post : Iterative Letter Combinations of a Phone Number



Print all Possible Words from Phone Digits
Visit Course explore course icon

Similar Reads