LinkedIn | Phone Interview | Senior Software Engineer Application
Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2025-05-18Added By Anonymous
Source: Link
I was asked this question in the interview:
Given the standard mapping from English letters to digits on a phone keypad (1 → "" 2 -> a,b,c 3 -> d,e,f 4 -> g,h,i 5 -> j,k,l 6 -> m,n,o 7 -> p,q,r,s 8 -> t,u,v 9 -> w,x,y,z),
write a program that outputs all words that can be formed from any n-digit phone number from the list of given KNOWN_WORDS considering the mapping mentioned above.
KNOWN_WORDS= ['careers', 'linkedin', 'hiring', 'interview', 'linkedgo']
phoneNumber: 2273377
Output: ['careers']
phoneNumber: 54653346
Output: ['linkedin', 'linkedgo']
Solution:
1public class WordFinderFromPhoneNumber {
2
3 private static final String[] KEYBOARD = {
4 "", // 0
5 "", // 1
6 "abc", // 2
7 "def", // 3
8 "ghi", // 4
9 "jkl", // 5
10 "mno", // 6
11 "pqrs", // 7
12 "tuv", // 8
13 "wxyz" // 9
14 }; // Already Given
15
16 private static final List<String> KNOWN_WORDS = Arrays.asList(
17 "careers", "linkedin", "hiring", "interview", "linkedgo"
18 ); // Already Given
19
20 private TrieNode root;
21
22 public WordFinderFromPhoneNumber() {
23 root = new TrieNode();
24 buildTrieNode(KNOWN_WORDS);
25 }
26
27 public List<String> wordsFromPhoneNumbers(String phoneNumber) {
28 List<String> result = new ArrayList<>();
29 Map<Character, Set<Character>> digitToCharMap = new HashMap<>();
30
31 for (int i = 2; i <= 9; i++) {
32 char digitChar = (char) (i + '0');
33 for (char ch : KEYBOARD[i].toCharArray()) {
34 digitToCharMap.computeIfAbsent(digitChar, x -> new HashSet<>()).add(ch);
35 }
36 }
37
38 backtracking(phoneNumber, 0, digitToCharMap, result, root);
39 return result;
40 }
41
42 private void buildTrieNode(List<String> words) {
43 for (String word : words) {
44 TrieNode curr = root;
45 for (char c : word.toCharArray()) {
46 curr.childrens.putIfAbsent(c, new TrieNode());
47 curr = curr.childrens.get(c);
48 }
49 curr.word = word;
50 }
51 }
52
53 private void backtracking(String digits, int index, Map<Character, Set<Character>> map,
54 List<String> result, TrieNode curr) {
55 if (index == digits.length()) {
56 if (!curr.word.isEmpty()) {
57 result.add(curr.word);
58 }
59 return;
60 }
61
62 char digit = digits.charAt(index);
63 if (!map.containsKey(digit)) return;
64
65 for (char letter : map.get(digit)) {
66 if (curr.childrens.containsKey(letter)) {
67 backtracking(digits, index + 1, map, result, curr.childrens.get(letter));
68 }
69 }
70 }
71
72 private static class TrieNode {
73 Map<Character, TrieNode> childrens = new HashMap<>();
74 String word = "";
75 }Even after giving this solution, got the rejection email.