Longest Word in Dictionary through Deleting (LeetCode 524): Solution and Explanation

Medium
Array
Two Pointers
String
Sorting

Find the longest dictionary word you can get by deleting letters from s. Ties go to the lexicographically smallest word, and if no word fits, return the empty string.

Intuition

Deleting letters never changes the order of the letters that stay. So a word can be formed from s exactly when its letters appear in s in the same order, which means it is a subsequence of s.

Checking one subsequence is a classic two-pointer walk. Move through s one letter at a time and advance a pointer into the word only when the letters match. If that pointer reaches the end of the word, the word fits.

You only need to remember the best word so far. A word that is shorter, or the same length but not smaller, can never replace it, so you can skip it before scanning s at all.

Approach: Two-pointer subsequence check per word

  1. Set best = "".
  2. For each word, skip it if it is shorter than best, or the same length and not lexicographically smaller.
  3. Otherwise set i = 0 and walk through s. Whenever the current letter equals word[i], move i forward.
  4. If i == len(word) after the walk, the word is a subsequence of s, so make it the new best.
  5. Return best after the last word.

Step-by-step example

s = "abpcplea", dictionary = ["ale","apple","monkey","plea"]
  1. "ale" beats the empty best. Scanning s matches a at 0, l at 5 and e at 6, so best becomes "ale".
  2. "apple" is longer. Scanning matches a at 0, p at 2, p at 4, l at 5 and e at 6, so best becomes "apple".
  3. "monkey" is longer still, but s has no m, so i stays at 0 and the word is rejected.
  4. "plea" is shorter than "apple", so it is skipped without a scan.
  5. Return "apple".

Code: Python, Java, C++

1class Solution:
2    def findLongestWord(self, s: str, dictionary: List[str]) -> str:
3        best = ""
4        for word in dictionary:
5            if len(word) < len(best) or (len(word) == len(best) and word >= best):
6                continue
7            i = 0
8            for ch in s:
9                if i < len(word) and ch == word[i]:
10                    i += 1
11            if i == len(word):
12                best = word
13        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(d * |s|)

Each of the d words that is not skipped takes one pass over s. The length and order checks add at most the total length of the words.

Space

O(1)

Only two pointers and a reference to the best word are kept.

Other approaches

Sort, then return the first match (time O(d log d * L + d * |s|), space O(d))

Sort the dictionary by length descending, then alphabetically, and return the first word that is a subsequence of s. Simple, but the sort costs extra time and memory.

Next-position table (time O(26 * |s| + total word length), space O(26 * |s|))

Precompute, for every index of s and every letter, the next index where that letter appears. Each word then takes O(len(word)) to check, which pays off when the dictionary is large.

Common mistakes

  • Checking whether the word's letters merely appear in s. They must appear in the same order, so "cb" does not fit in "abc".
  • Breaking ties by dictionary order instead of lexicographic order. Among equal lengths the smaller word wins, wherever it sits in the list.
  • Comparing with > instead of >= in the skip test, which rescans equal words for nothing.

Frequently asked questions

Why does a greedy match work for the subsequence check?

Matching each letter of the word at its earliest possible position in s leaves the most room for the letters after it, so if any way of matching exists, the greedy one finds it.

Is the early skip required?

No, it is an optimization. Without it the answer is the same, but every word costs a full pass over s.

What if two words are identical?

The second copy is the same length and not smaller, so it is skipped. The answer does not change.