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: "good"
💡 Note: Both 'word' and 'good' have length 4 and can be formed as subsequences. Since they have equal length, we choose the lexicographically smaller one: 'good' < '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 Deleting INPUT String s: "wordgoodgoodgoodword" Characters (20 total): w o r d g o o d g o o d g o o d w o r d Dictionary: "word" len: 4 "good" len: 4 "goodword" len: 8 (longest) Find longest subsequence match ALGORITHM STEPS 1 Sort Dictionary By length desc, then lex order 1. "goodword" 2. "good" 3. "word" 2 Subsequence Check Two-pointer technique 3 Match "goodword" Traverse s with dict word s: w o r d g o o d g o o d w o r d g o o d w o r d Pointers: i=0..19, j=0..7 Match found! j reached end 4 Return First Match Sorted order ensures optimal O(n*m*k) time complexity FINAL RESULT Longest Matching Word: "goodword" Verification: Length: 8 characters Status: [OK] Subsequence of s s = "word good goodgood word " Highlighted chars form "goodword" Output: "goodword" "word"(4) < "goodword"(8) Key Insight: The two-pointer technique efficiently checks if a dictionary word is a subsequence of s. By sorting the dictionary (longest first, then lexicographically), we can return the first match found, guaranteeing both maximum length and smallest lexicographical order. TutorialsPoint - Longest Word in Dictionary through Deleting | Optimal Solution (Two-Pointer + Sorting)
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