Longest Word in Dictionary through Deleting - Problem
Imagine you have a master string and a dictionary of words. Your goal is to find the longest word from the dictionary that can be formed by deleting some characters from the master string (while keeping the relative order of remaining characters).
For example, if your master string is "wordgoodgoodgoodbestword" and your dictionary contains ["word", "good", "best", "good"], you can form:
"word"by keeping characters at positions [0,1,2,3]"good"by keeping characters at positions [4,5,6,7]"best"by keeping characters at positions [17,18,19,20]
The longest word is "word", "good", and "best" (all length 4), but lexicographically, "best" comes first, so we return "best".
Key Rules:
- Characters must maintain their relative order from the original string
- If multiple words have the same length, return the lexicographically smallest one
- If no word can be formed, return an empty string
Input & Output
example_1.py โ Basic Example
$
Input:
s = "wordgoodgoodgoodbestword", dictionary = ["word","good","best","word","good"]
โบ
Output:
"best"
๐ก Note:
All words "word", "good", and "best" can be formed by deleting characters. Among the longest words (length 4), "best" is lexicographically smallest.
example_2.py โ Single Character
$
Input:
s = "abcr", dictionary = ["a","aa","aaa","aaaa"]
โบ
Output:
"a"
๐ก Note:
Only "a" can be formed as a subsequence. "aa", "aaa", and "aaaa" cannot be formed because there's only one 'a' in the string.
example_3.py โ Empty Result
$
Input:
s = "abc", dictionary = ["xyz", "def"]
โบ
Output:
""
๐ก Note:
None of the dictionary words can be formed as subsequences of "abc", so we return an empty string.
Constraints
- 1 โค s.length โค 1000
- 1 โค dictionary.length โค 1000
- 1 โค dictionary[i].length โค 1000
- s and dictionary[i] consist of lowercase English letters only
Visualization
Tap to expand
Understanding the Visualization
1
Prepare the Excavation
Sort your dictionary of target words by priority (longest first, then alphabetically)
2
Begin Excavation
For each target word, use two careful pointers - one tracking your position in the inscription, one in the target word
3
Match Characters
When you find a matching character, advance both pointers. Otherwise, continue scanning the inscription
4
Discover the Treasure
When you successfully match all characters of a word, you've found your archaeological treasure!
Key Takeaway
๐ฏ Key Insight: By sorting the dictionary strategically and using two pointers for subsequence checking, we can find the optimal word efficiently while ensuring the first match we find is always the best possible answer.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code