Question
Write an autocomplete class that returns all dictionary words with a given prefix.
eg.
1 2 3 4 |
dict: {"abc", "acd", "bcd", "def", "a", "aba"} prefix: "a" -> "abc", "acd", "a", "aba" prefix: "b" -> "bcd" |
Once you think that you’ve solved the problem, click below to see the solution.
As always, remember that practicing coding interview questions is as much about how you practice as the question itself. Make sure that you give the question a solid go before skipping to the solution. Ideally if you have time, write out the solution first by hand and then only type it into your computer to verify your work once you've verified it manually. To learn more about how to practice, check out this blog post.
Solution
How was that problem? You can check out the solution in the video below.
Here is the source code for the solution shown in the video (Github):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
// Trie node class private class Node { String prefix; HashMap<Character, Node> children; // Does this node represent the last character in a word? boolean isWord; private Node(String prefix) { this.prefix = prefix; this.children = new HashMap<Character, Node>(); } } // The trie private Node trie; // Construct the trie from the dictionary public Autocomplete(String[] dict) { trie = new Node(""); for (String s : dict) insertWord(s); } // Insert a word into the trie private void insertWord(String s) { // Iterate through each character in the string. If the character is not // already in the trie then add it Node curr = trie; for (int i = 0; i < s.length(); i++) { if (!curr.children.containsKey(s.charAt(i))) { curr.children.put(s.charAt(i), new Node(s.substring(0, i + 1))); } curr = curr.children.get(s.charAt(i)); if (i == s.length() - 1) curr.isWord = true; } } // Find all words in trie that start with prefix public List<String> getWordsForPrefix(String pre) { List<String> results = new LinkedList<String>(); // Iterate to the end of the prefix Node curr = trie; for (char c : pre.toCharArray()) { if (curr.children.containsKey(c)) { curr = curr.children.get(c); } else { return results; } } // At the end of the prefix, find all child words findAllChildWords(curr, results); return results; } // Recursively find every child word private void findAllChildWords(Node n, List<String> results) { if (n.isWord) results.add(n.prefix); for (Character c : n.children.keySet()) { findAllChildWords(n.children.get(c), results); } } |
Did you get the right answer to this coding interview question? Please share your thoughts in the comments below.