Search~20 min2s · 256 MBtarget O(total letters + kept calls) time, O(total letters) spaceclassic twin: lc-17backtracking
A search app lets people type a word on a phone keypad. Each digit from 2 to 9 stands for the letters on its key. Digit 2 has a, b and c, and digit 9 has w, x, y and z.
The app has a word list. For the digits a person typed, it must find the words the digits can spell.
Your team lead says: Return the words in alphabetical order, and do not build letter strings that no word starts with.
Write keypad_words(digits, words).
abc, 3 for def, 4 for ghi, 5 for jkl, 6 for mno, 7 for pqrs, 8 for tuv and 9 for wxyz.words holds different words. Return the words that the digits spell, in alphabetical order.Input: digits = "4663", words = ["good", "gone", "home", "hood", "hoof", "goof", "idle", "hold", "gold", "hello"]
Output: ["gone", "good", "goof", "home", "hood", "hoof"]The digits 4, 6, 6 and 3 offer the letters ghi, mno, mno and def. The search extends a text only when some word starts with it. The words idle, hold, gold and hello are never spelled.
| Word | Calls made so far when it is saved |
|---|---|
| gone | 5 |
| good | 7 |
| goof | 8 |
| home | 12 |
| hood | 14 |
| hoof | 15 |
The search makes 16 calls. Building every letter string would make 121.
Input: digits = "22", words = ["aa", "bc", "ca", "ad"]
Output: ["aa", "bc", "ca"]The word ad has a d, and the key 2 has no d. The words aa, bc and ca use only letters from abc.
Input: digits = "7", words = ["a", "p", "s"]
Output: ["p", "s"]The key 7 offers pqrs. The words p and s are spelled. The word a is not on key 7.
1 ≤ digits.length ≤ 12, and every digit is 2 to 91 ≤ words.length ≤ 5,0001 ≤ words[i].length ≤ 12, lowercase letters, and all words are differentTwelve digits on keys with four letters offer 4^12 = 16,777,216 letter strings, so building every one takes far too long. A word list of 5,000 words has at most 60,000 prefixes, and the search enters only the texts that a word starts with. The first large test makes 21,163 calls. The recursion is at most 12 calls deep.