Given an integer array containing digits from **[0, 9]**, the task is to print all possible letter combinations that the numbers could represent.

A mapping of digit to letters (just like on the telephone buttons) is being followed. **Note** that **0** and **1** do not map to any letters. All the mapping are shown in the image below:

**Example:**

Input:arr[] = {2, 3}

Output:ad ae af bd be bf cd ce cf

Input:arr[] = {9}

Output:w x y z

**Approach:** Now let us think how we would approach this problem without doing it in an iterative way. A recursive solution is intuitive and common. We keep adding each possible letter recursively and this will generate all the possible strings.

Let us think about how we can build an iterative solution using the recursive one. Recursion is possible through the use of a stack. So if we use a stack instead of a recursive function will that be an iterative solution? One could say so speaking technically but we then aren’t really doing anything different in terms of logic.

A Stack is a LIFO DS. Can we use another Data structure? What will be the difference if we use a FIFO DS? Let’s say a queue. Since BFS is done by queue and DFS by stack is there any difference between the two?

The difference between DFS and BFS is similar to this question. In DFS we will find each path possible in the tree one by one. It will perform all steps for a path first whereas BFS will build all paths together one step at a time.

So, a queue would work perfectly for this question. The only difference between the two algorithms using queue and stack will be the way in which they are formed. Stack will form all strings completely one by one whereas the queue will form all the strings together i.e. after x number of passes all the strings will have a length of x.

Below is the implementation of the above approach:

## C++

*chevron_right*

*filter_none*

## Python

*chevron_right*

*filter_none*

**Output:**

ad ae af bd be bf cd ce cf

## Recommended Posts:

- Implement a Phone Directory
- Print all the combinations of a string in lexicographical order
- Python regex to find sequences of one upper case letter followed by lower case letters
- Python Program for Iterative Quick Sort
- Python Program for Iterative Merge Sort
- Python Program for Binary Search (Recursive and Iterative)
- Iterative Boundary traversal of Complete Binary tree
- Iterative Method to find Height of Binary Tree
- Check whether a given Binary Tree is Complete or not | Set 1 (Iterative Solution)
- Iterative Method To Print Left View of a Binary Tree
- Number which has the maximum number of distinct prime factors in the range M to N
- Number of ways to calculate a target number using only array elements
- Check if the binary representation of a number has equal number of 0s and 1s in blocks
- Python Program to Find the Number Occurring Odd Number of Times
- Represent a number as a sum of maximum possible number of Prime Numbers