Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Print all possible words from phone digits
Next article icon

Print all possible words from phone digits

Last Updated : 28 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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]

Table of Content

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

[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



Next Article
Print all possible words from phone digits

K

kartik
Improve
Article Tags :
  • Strings
  • Mathematical
  • Recursion
  • DSA
  • Arrays
  • Amazon
  • Flipkart
  • Samsung
  • Snapdeal
  • Accolite
  • Zoho
  • OYO
  • phone-keypad
Practice Tags :
  • Accolite
  • Amazon
  • Flipkart
  • Samsung
  • Snapdeal
  • Zoho
  • Arrays
  • Mathematical
  • Recursion
  • Strings

Similar Reads

    Print all Possible Decodings of a given Digit Sequence
    Given the numeric string str, where 1 represents 'a', 2 represents 'b', ..., 26 represents 'z', the task is to print all possible alphabetical strings that can be obtained from str. Examples: Input: str = "1123" Output: aabc kbc alc aaw kw Explanation: The given string can be splitted as: 1) "1123"
    11 min read
    Print all numbers up to N in words in lexicographical order
    Given an integer N, the task is to print all numbers from 1 to N (0 < N < 100000) in words in lexicographical order. Examples : Input: N = 11Output: eight, eleven, five, four, nine, one, seven, six, three, twoExplanation: The numbers from 1 to N is 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11. Their resp
    8 min read
    Find all strings in lexicographic order possible by replacing digits with 'x', 'y' or 'z'
    Given a string str, consisting of lower case English alphabets and digits(0-9), the task is to print all possible strings in lexicographic order that can be formed by replacing each occurrence of a digit with either 'x', 'y' or 'z'. Example: Input: str = "a1b2"Output: axbx axby axbz aybx ayby aybz a
    6 min read
    Find digits present in given jumbled String
    Given a string s of length N, containing digits written in words but in jumbled form, the task is to find out the digits present in the string in word form and arrange them in sorted order. Examples: Input: s = "ozerotwneozero"Output: 0012Explanation: The string can be arranged as "zerozeroonetwo".T
    11 min read
    Print all possible combinations of the string by replacing '$' with any other digit from the string
    Given a number as a string where some of the digits are replaced by a '$', the task is to generate all possible number by replacing the '$' with any of the digits from the given string.Examples: Input: str = "23$$" Output: 2322 2323 2332 2333Input: str = "$45" Output: 445 545 Approach: Find all the
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences