Problem 524

Abstract / Summary

Find the longest string in a list that can be made from another string by deleting some letters.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0524.py

class Solution:
    def findLongestWord(self, s: str, dictionary: List[str]) -> str:
        dictionary.sort(key = lambda x : len(x), reverse = True) # longest words first

        # count letters
        fingerprint = defaultdict(int)
        for c in s:
            fingerprint[c] += 1

        result = ""
        for w in dictionary:
            # longest one found
            if len(result) > len(w):
                break

            # count letters
            freq = defaultdict(int)
            for c in w:
                freq[c] += 1

            # need to have enough matching letters
            if not all(f in fingerprint and freq[f] <= fingerprint[f] for f in freq):
                continue

            # now check their order
            pos = 0
            for c in s:
                if c != w[pos]:
                    continue

                pos += 1
                # fully matched
                if pos == len(w):
                    if not result or result > w:
                        result = w
                    break

        return result
38 lines | 1115 bytes | submitted October 13, 2023 | GitHub   28% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 53% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Sorting
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the “longest word in dictionary that is a subsequence of a given string” problem. It first orders the candidate words by length, builds a character frequency map for the source string, then iterates through the sorted dictionary to find the first word that satisfies both a frequency constraint and the subsequence ordering constraint. The algorithm stops early when a longer word has already been found, guaranteeing that the returned word is the longest possible and, in case of ties, the lexicographically smallest.

Sorting Dictionary

The code begins by arranging the dictionary so that longer candidates are examined before shorter ones:

dictionary.sort(key = lambda x : len(x), reverse = True) # longest words first

By sorting in descending length order, the loop can break as soon as it encounters a word shorter than the current best result, eliminating unnecessary checks for the remaining entries.

Building Fingerprint

A frequency map of the source string s is constructed using a defaultdict(int). Each character increments its count:

fingerprint = defaultdict(int)
for c in s:
    fingerprint[c] += 1

This map, called fingerprint, records how many times each character appears in s. It is later used to verify that a candidate word does not require more occurrences of any character than are available.

Iterating Candidates

The main loop walks through the sorted dictionary. An early-exit condition checks whether the current best result is already longer than the word under consideration:

for w in dictionary:
    if len(result) > len(w):
        break

If the result is longer, no later word can surpass it because the list is sorted by decreasing length.

Frequency Check

For each candidate, a fresh frequency map freq is built:

freq = defaultdict(int)
for c in w:
    freq[c] += 1

The algorithm then ensures that every character required by the candidate appears at least as many times in s:

if not all(f in fingerprint and freq[f] <= fingerprint[f] for f in freq):
    continue

If any character fails this test, the candidate is rejected immediately, avoiding the more expensive subsequence scan.

Order Verification

When the frequency condition passes, the code proceeds to verify that the candidate is a subsequence of s. It walks through s while tracking a position index pos within the candidate word:

pos = 0
for c in s:
    if c != w[pos]:
        continue
    pos += 1
    if pos == len(w):
        if not result or result > w:
            result = w
        break

Each matching character advances pos. When pos reaches the length of the candidate, the word has been fully matched in order, and it becomes the new result if it is lexicographically smaller than the current result (or if no result exists yet).

Result Selection

The result variable is updated only when a full subsequence match is found and the candidate is either the first match or lexicographically smaller than the existing result. Because the dictionary is processed from longest to shortest, the first successful match is guaranteed to be of maximal length, and the lexicographic comparison resolves ties.

Edge Cases Handled

The implementation gracefully handles several edge conditions:

  • An empty source string s yields an empty fingerprint, causing every frequency check to fail, and the function returns an empty string.
  • An empty dictionary results in the loop never executing, leaving result as an empty string.
  • Candidates containing characters not present in s are filtered out by the frequency check, preventing unnecessary subsequence scans.
  • Words that require more occurrences of a character than s provides are also rejected early, thanks to the freq[f] <= fingerprint[f] condition.
  • When multiple words share the same maximum length, the lexicographic comparison (result > w) ensures the smallest one is chosen.
  • The inner subsequence loop terminates as soon as a full match is detected, avoiding extra iterations over the remainder of s.

Performance Optimizations

The code incorporates several optimizations that reduce the overall work:

  • Sorting the dictionary in descending length order enables an early break once a longer result is found, cutting off the processing of all shorter candidates.
  • The frequency map for s is built once outside the main loop, avoiding repeated scans of s for each candidate.
  • The per-candidate frequency map freq is constructed only for the current word, and the subsequent all check eliminates candidates that cannot possibly match, sparing the more costly subsequence verification.
  • The subsequence verification loop stops immediately after a full match, preventing unnecessary traversal of the remaining characters in s.
  • Lexicographic comparison is performed only after a successful subsequence match, minimizing string comparisons.

Collectively, these strategies keep the algorithm focused on the most promising candidates and avoid redundant work, delivering an efficient solution for the problem at hand.

written by openai gpt

ELI5 - Simplified Explanation

Imagine having a big bag of letters and a list of secret words written on cards. To find the winner, first sort the cards so the longest words are right on top.

Take the starting bag of letters and count how many of each kind are inside. Keep this count handy so it is easy to check if a word has enough letters to be made.

Go through the list of word cards one by one. For each word, first check if there are enough letters in the bag to build it. If a card needs more letters than are in the bag, move to the next card.

If there are enough letters, check if the letters appear in the correct order. Walk through the giant bag of letters from start to finish. Every time a letter matches the one needed for the word, move to the next letter of that word. If every letter is found in the right sequence, this word is a winner.

Keep track of the best word found so far. Since the cards were sorted by length, the first valid word found that is the longest becomes the favorite. If two words have the same length, pick the one that comes first in the alphabet. Continue through the cards and hold onto the best one until the very end.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.78 | σ = 1.66

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Rust Go TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fengvyi C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fengvyi C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak C++
YuriSpiridonov Python
zfang399 C++
38 links | 24 authors | 9 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

5 medium
6 solutions   October 13, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality