In this string problem, you are given a string s and an array of dictionary words. You need to find the longest word in the dictionary that can be formed by deleting some (or zero) characters from the string s. If multiple valid words have the same maximum length, you must return the lexicographically smallest one.
This is a classic Two Pointers and string parsing question. Interviewers use it to evaluate whether a candidate can write an efficient subsequence validation function. It tests optimization skills; checking subsequences can be computationally expensive, so candidates are pushed to organize their logic to minimize unnecessary comparisons and handle strict tie-breaking conditions cleanly.
This problem relies on Two Pointers and Iterative Search. For each word in the dictionary, you use a two-pointer approach to check if it is a valid subsequence of s. One pointer tracks s, and the other tracks the dictionary word. If it is a valid subsequence, you compare its length and lexicographical value against your currently stored "best" word, updating the best word if the new one is longer, or same length but alphabetically smaller.
String s = "abpcplea", Dictionary = ["ale", "apple", "monkey", "plea"].
"ale": Is it a subsequence of "abpcplea"? Yes. Best = "ale"."apple": Is it a subsequence? Yes. Length 5 is . Best = "apple"."monkey": Is it a subsequence? No ('m' is missing)."plea": Is it a subsequence? Yes. Length is 4. Length 4 is not . Ignore.
The final result is "apple".
If the dictionary had both "apple" and "apply", and both were subsequences, "apple" would win because it comes first alphabetically.A common error is trying to generate all possible subsequences of s and checking if they exist in the dictionary. Since a string of length has subsequences, this approach will immediately cause a Time Limit Exceeded error. You must iterate over the dictionary words and validate them against s, not the other way around. Another mistake is sorting the entire dictionary first; while it works, it is mathematically slower than just maintaining a running "best" string during a single linear scan.
For the Longest Word in Dictionary through Deleting interview pattern, isolate your logic into a helper function isSubsequence(word, s). Keeping this loop clean (advancing the word pointer only when characters match, while always advancing the s pointer) proves to the interviewer that you understand separation of concerns and modular code design.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Longest Uncommon Subsequence II | Medium | Solve | |
| The k Strongest Values in an Array | Medium | Solve | |
| Expressive Words | Medium | Solve | |
| Sentence Similarity III | Medium | Solve | |
| Meeting Scheduler | Medium | Solve |