Skip to content

Commit f31f749

Browse files
committed
Add letter combinations algorithm
1 parent d33313d commit f31f749

File tree

7 files changed

+177
-0
lines changed

7 files changed

+177
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,7 @@ List of Programs related to data structures and algorithms
197197
| 5 | Verify Common Elements | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/5.verifyCommonElements/verifyCommonElements.js) | [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/5.verifyCommonElements/verifyCommonElements.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/5.verifyCommonElements/verifyCommonElements.md) | Easy | Using Map methods |
198198
| 6 | Longest consequtive sequence |[Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/6.longestConsecutiveSequence/longestConsecutiveSequence.js) | [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/6.longestConsecutiveSequence/longestConsecutiveSequence.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/6.longestConsecutiveSequence/longestConsecutiveSequence.md) | Medium | Find sequence using set or hash table |
199199
| 7 | Valid Sudoku | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/7.validSudoku/validSudoku.js) | [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/7.validSudoku/validSudoku.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/7.validSudoku/validSudoku.md) | Medium | Using Map and Set methods |
200+
| 8 | Letter combinations | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/8.letterCombinations/letterCombinations.js) | [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/8.letterCombinations/letterCombinations.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/8.letterCombinations/letterCombinations.md) | Medium | Backtracking with hash table mapping |
200201

201202
## Sorting
202203

src/images/calculator.png

102 KB
Loading

src/images/letter-combinations.png

38.8 KB
Loading
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package java1.algorithms.hashmap.letterCombinations;
2+
3+
import java.util.ArrayList;
4+
import java.util.HashMap;
5+
import java.util.List;
6+
import java.util.Map;
7+
8+
class LetterCombinations {
9+
10+
private static List<String> letterCombinations(String digits){
11+
List<String> combinations = new ArrayList<>();
12+
if(digits.isEmpty()) {
13+
return combinations;
14+
}
15+
16+
Map<Character, String> digitToChar = new HashMap<>();
17+
digitToChar.put('2', "abc");
18+
digitToChar.put('3', "def");
19+
digitToChar.put('4', "ghi");
20+
digitToChar.put('5', "jkl");
21+
digitToChar.put('6', "mno");
22+
digitToChar.put('7', "pqrs");
23+
digitToChar.put('8', "tuv");
24+
digitToChar.put('9', "wxyz");
25+
26+
backtrack(0, "", digits, digitToChar, combinations);
27+
return combinations;
28+
}
29+
30+
private static void backtrack(int i, String currStr, String digits, Map<Character, String> digitToChar, List<String> combinations) {
31+
if(digits.length() == currStr.length()) {
32+
combinations.add(currStr);
33+
return;
34+
}
35+
36+
for (char ch : digitToChar.get(digits.charAt(i)).toCharArray()) {
37+
backtrack(i+1, currStr+ch, digits, digitToChar, combinations);
38+
}
39+
}
40+
public static void main(String[] args) {
41+
String digits1 = "24";
42+
String digits2 = "";
43+
System.out.println(letterCombinations(digits1));
44+
System.out.println(letterCombinations(digits2));
45+
46+
}
47+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
**Problem statement:**
2+
Given a string `digits` contain digits 2-9 inclusive, and each digit(except 1) is mapped to a set of characters. Return all possible letter combinations that the number could represent.
3+
4+
**Note:** The output can be written in any order. The mapping of digits to letters is shown below:
5+
6+
![Screenshot](../../../../images/calculator.png)
7+
8+
## Examples:
9+
Example 1:
10+
11+
Input: digits = "24"
12+
13+
Output: ["ag","ah","ai","bg","bh","bi","cg","ch","ci"]
14+
15+
![Screenshot](../../../../images/letter-combinations.png)
16+
17+
Example 2:
18+
19+
Input: digits = ""
20+
21+
Output: []
22+
23+
24+
**Algorithmic Steps**
25+
This problem is solved with the help of backtracking recursive solution by generating all possible combinations of letters for respective digits. The mapping between digits(2-9) and letters is taken care by map datastructure. The algorithmic approach can be summarized as follows:
26+
27+
1. Initialize an empty array `combinations` to store the final letter combinations.
28+
29+
2. Handle the edge case by returning empty combinations array if the given string `digits` is empty.
30+
31+
3. Create a digit(2-9) to character mapping using a map called `digitToChar`.
32+
33+
4. Create a backtracking function to generate letter combinations for given digits string.
34+
1. Add a base case to include letter combination for given string. i.e If the length of digits string is equals to current string(`digits`), add that current string to `combinations` and return.
35+
2. Iterate over all possible letters of a current digit. For each iteration, recursively call backtracking function with incremented index(`i+1`) and updated current string(`currStr`).
36+
3. Continue this process until all possible combinations added.
37+
38+
5. Invoke the backtracking function with in main function. The function is called with index 0 and empty current string.
39+
40+
6. Return `combinations` indicating the possible combinations of digits string.
41+
42+
43+
**Time and Space complexity:**
44+
This algorithm has a time complexity of `O(4^n)`, Where `n` is the number of digits in a given string. This is because the backtrack function needs to generate all possible combinations of letters. For each digit, there are upto 4 possible characters(for example, 7-> "pqrs" and 9->"wxyz"). If there are `n` digits in a given string, the maximum number of possible combinations is `O(4^n)`. Building each combination involves appending character one by one, and each combination takes `O(n)`. Hence, the overall time complexity ois `O(n * 4^n)`.
45+
46+
Here, the maximum possible combinations of letters are `4^n` ,and each combination has a length of `n`. So it takes a space complexity of `O(n * 4^n)`.
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
function letterCombinations(digits){
2+
let combinations = [];
3+
if(digits.length === 0) {
4+
return combinations;
5+
}
6+
let digitToChar = new Map();
7+
8+
digitToChar.set('2', "abc");
9+
digitToChar.set('3', "def");
10+
digitToChar.set('4', "ghi");
11+
digitToChar.set('5', "jkl");
12+
digitToChar.set('6', "mno");
13+
digitToChar.set('7', "pqrs");
14+
digitToChar.set('8', "tuv");
15+
digitToChar.set('9', "wxyz");
16+
17+
backtrack(0, "", digits, digitToChar, combinations);
18+
19+
return combinations;
20+
}
21+
22+
function backtrack(i, currStr, digits, digitToChar, combinations){
23+
if(digits.length === currStr.length) {
24+
combinations.push(currStr);
25+
return;
26+
}
27+
28+
for (const ch of digitToChar.get(digits[i])) {
29+
backtrack(i+1, currStr+ch, digits, digitToChar, combinations);
30+
}
31+
}
32+
33+
let digits1 = "24";
34+
let digits2 = "";
35+
console.log(letterCombinations(digits1));
36+
console.log(letterCombinations(digits2));
37+
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
**Problem statement:**
2+
Given a string `digits` contain digits 2-9 inclusive, and each digit(except 1) is mapped to a set of characters. Return all possible letter combinations that the number could represent.
3+
4+
**Note:** The output can be written in any order. The mapping of digits to letters is shown below:
5+
6+
![Screenshot](../../../../images/calculator.png)
7+
8+
## Examples:
9+
Example 1:
10+
11+
Input: digits = "24"
12+
13+
Output: ["ag","ah","ai","bg","bh","bi","cg","ch","ci"]
14+
15+
![Screenshot](../../../../images/letter-combinations.png)
16+
17+
Example 2:
18+
19+
Input: digits = ""
20+
21+
Output: []
22+
23+
24+
**Algorithmic Steps**
25+
This problem is solved with the help of backtracking recursive solution by generating all possible combinations of letters for respective digits. The mapping between digits(2-9) and letters is taken care by map datastructure. The algorithmic approach can be summarized as follows:
26+
27+
1. Initialize an empty array `combinations` to store the final letter combinations.
28+
29+
2. Handle the edge case by returning empty combinations array if the given string `digits` is empty.
30+
31+
3. Create a digit(2-9) to character mapping using a map called `digitToChar`.
32+
33+
4. Create a backtracking function to generate letter combinations for given digits string.
34+
1. Add a base case to include letter combination for given string. i.e If the length of digits string is equals to current string(`digits`), add that current string to `combinations` and return.
35+
2. Iterate over all possible letters of a current digit. For each iteration, recursively call backtracking function with incremented index(`i+1`) and updated current string(`currStr`).
36+
3. Continue this process until all possible combinations added.
37+
38+
5. Invoke the backtracking function with in main function. The function is called with index 0 and empty current string.
39+
40+
6. Return `combinations` indicating the possible combinations of digits string.
41+
42+
43+
**Time and Space complexity:**
44+
This algorithm has a time complexity of `O(4^n)`, Where `n` is the number of digits in a given string. This is because the backtrack function needs to generate all possible combinations of letters. For each digit, there are upto 4 possible characters(for example, 7-> "pqrs" and 9->"wxyz"). If there are `n` digits in a given string, the maximum number of possible combinations is `O(4^n)`. Building each combination involves appending character one by one, and each combination takes `O(n)`. Hence, the overall time complexity ois `O(n * 4^n)`.
45+
46+
Here, the maximum possible combinations of letters are `4^n` ,and each combination has a length of `n`. So it takes a space complexity of `O(n * 4^n)`.

0 commit comments

Comments
 (0)