Longest Word in Dictionary through Deleting (LeetCode 524): Solution and Explanation
Find the longest dictionary word you can get by deleting letters from s. Ties go to the lexicographically smallest word, and if no word fits, return the empty string.
Intuition
Deleting letters never changes the order of the letters that stay. So a word can be formed from s exactly when its letters appear in s in the same order, which means it is a subsequence of s.
Checking one subsequence is a classic two-pointer walk. Move through s one letter at a time and advance a pointer into the word only when the letters match. If that pointer reaches the end of the word, the word fits.
You only need to remember the best word so far. A word that is shorter, or the same length but not smaller, can never replace it, so you can skip it before scanning s at all.
Approach: Two-pointer subsequence check per word
- Set
best = "". - For each word, skip it if it is shorter than
best, or the same length and not lexicographically smaller. - Otherwise set
i = 0and walk through s. Whenever the current letter equalsword[i], moveiforward. - If
i == len(word)after the walk, the word is a subsequence of s, so make it the newbest. - Return
bestafter the last word.
Step-by-step example
s = "abpcplea", dictionary = ["ale","apple","monkey","plea"]
- "ale" beats the empty best. Scanning s matches a at 0, l at 5 and e at 6, so best becomes "ale".
- "apple" is longer. Scanning matches a at 0, p at 2, p at 4, l at 5 and e at 6, so best becomes "apple".
- "monkey" is longer still, but s has no m, so i stays at 0 and the word is rejected.
- "plea" is shorter than "apple", so it is skipped without a scan.
- Return "apple".
Code: Python, Java, C++
1class Solution:
2 def findLongestWord(self, s: str, dictionary: List[str]) -> str:
3 best = ""
4 for word in dictionary:
5 if len(word) < len(best) or (len(word) == len(best) and word >= best):
6 continue
7 i = 0
8 for ch in s:
9 if i < len(word) and ch == word[i]:
10 i += 1
11 if i == len(word):
12 best = word
13 return best1class Solution {
2 public String findLongestWord(String s, List<String> dictionary) {
3 String best = "";
4 for (String word : dictionary) {
5 if (word.length() < best.length() || (word.length() == best.length() && word.compareTo(best) >= 0)) {
6 continue;
7 }
8 int i = 0;
9 for (int j = 0; j < s.length(); j++) {
10 if (i < word.length() && s.charAt(j) == word.charAt(i)) {
11 i++;
12 }
13 }
14 if (i == word.length()) {
15 best = word;
16 }
17 }
18 return best;
19 }
20}1class Solution {
2public:
3 string findLongestWord(string s, vector<string>& dictionary) {
4 string best = "";
5 for (const string& word : dictionary) {
6 if (word.size() < best.size() || (word.size() == best.size() && word >= best)) {
7 continue;
8 }
9 size_t i = 0;
10 for (char ch : s) {
11 if (i < word.size() && ch == word[i]) {
12 i++;
13 }
14 }
15 if (i == word.size()) {
16 best = word;
17 }
18 }
19 return best;
20 }
21};Time and space complexity
O(d * |s|)
Each of the d words that is not skipped takes one pass over s. The length and order checks add at most the total length of the words.
O(1)
Only two pointers and a reference to the best word are kept.
Other approaches
Sort, then return the first match (time O(d log d * L + d * |s|), space O(d))
Sort the dictionary by length descending, then alphabetically, and return the first word that is a subsequence of s. Simple, but the sort costs extra time and memory.
Next-position table (time O(26 * |s| + total word length), space O(26 * |s|))
Precompute, for every index of s and every letter, the next index where that letter appears. Each word then takes O(len(word)) to check, which pays off when the dictionary is large.
Common mistakes
- Checking whether the word's letters merely appear in s. They must appear in the same order, so "cb" does not fit in "abc".
- Breaking ties by dictionary order instead of lexicographic order. Among equal lengths the smaller word wins, wherever it sits in the list.
- Comparing with
>instead of>=in the skip test, which rescans equal words for nothing.
Frequently asked questions
Why does a greedy match work for the subsequence check?
Matching each letter of the word at its earliest possible position in s leaves the most room for the letters after it, so if any way of matching exists, the greedy one finds it.
Is the early skip required?
No, it is an optimization. Without it the answer is the same, but every word costs a full pass over s.
What if two words are identical?
The second copy is the same length and not smaller, so it is skipped. The answer does not change.