Longest Word in Dictionary through Deleting - Problem

Given a string s and a string array dictionary, return the longest string in the dictionary that can be formed by deleting some of the given string characters.

If there is more than one possible result, return the longest word with the smallest lexicographical order.

If there is no possible result, return the empty string.

Input & Output

Example 1 — Multiple Valid Words
$ Input: s = "wordgoodgoodgoodword", dictionary = ["word", "good", "goodword"]
Output: "goodword"
💡 Note: All three words can be formed from s by deleting characters: 'word' (length 4), 'good' (length 4), 'goodword' (length 8). 'goodword' is longest.
Example 2 — Lexicographical Tie-Breaking
$ Input: s = "wordgoodgoodgoodword", dictionary = ["word", "good", "best"]
Output: "word"
💡 Note: Both 'word' and 'good' have length 4 and can be formed. 'good' < 'word' lexicographically, so return 'good'. Wait, that's wrong. 'good' comes before 'word', so return 'good'.
Example 3 — No Valid Words
$ Input: s = "wordgoodgoodgoodword", dictionary = ["xyz", "abc"]
Output: ""
💡 Note: Neither 'xyz' nor 'abc' can be formed as subsequences of s, so return 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
Longest Word in Dictionary through Deletings = "wordgoodgoodgoodword"Dictionary Words:"word""good""goodword"✓ length 4✓ length 4✓ length 8All are subsequences, but "goodword" is longestOutput: "goodword"
Understanding the Visualization
1
Input
String s and dictionary of candidate words
2
Process
Check which words are subsequences of s
3
Output
Return longest word (lexicographically smallest if tie)
Key Takeaway
🎯 Key Insight: Sort dictionary to process longer words first, enabling early termination
Asked in
Google 35 Amazon 28 Microsoft 22 Apple 15
58.2K Views
Medium Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen