Leetcode•Apr 17, 2026
Longest Word in Dictionary through Deleting
Hazrat Ali
Leetcode
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.
Example 1:
Input: s = "abpcplea", dictionary = ["ale","apple","monkey","plea"] Output: "apple"
Example 2:
Input: s = "abpcplea", dictionary = ["a","b","c"] Output: "a"
Solution
var findLongestWord = function(s, dictionary) {
let result = "";
for (let word of dictionary) {
if (isSubsequence(word, s)) {
if (
word.length > result.length ||
(word.length === result.length && word < result)
) {
result = word;
}
}
}
return result;
};
function isSubsequence(word, s) {
let i = 0, j = 0;
while (i < word.length && j < s.length) {
if (word[i] === s[j]) i++;
j++;
}
return i === word.length;
}