Python 0648.py
class Solution:
def replaceWords(self, dictionary: List[str], sentence: str) -> str:
roots = set(dictionary)
result = []
for word in sentence.split():
found = False
current = ""
for c in word:
current += c
if current in roots:
result.append(current)
found = True
break
if not found:
result.append(word)
return " ".join(result)
Difficulty
and has an acceptance rate of about 69% (400k+ submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- String
- Trie
AI Disclaimer
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.
Code Walkthrough
Overview
The provided implementation solves the “replace words” problem by scanning each word in the input sentence and substituting it with the shortest root found in a given dictionary. The algorithm proceeds in three logical phases: preparation of the lookup structure, iterative processing of each word, and incremental prefix detection. By leveraging a hash-based container for constant-time membership tests and terminating the inner scan as soon as a matching root is discovered, the code achieves a streamlined execution path.
Preparation of the Dictionary
The first operation converts the list of root strings into a set, enabling rapid existence checks.
roots = set(dictionary)
Using a set eliminates duplicate entries automatically and provides O(1) average-case lookups, which is crucial when many words must be examined against the same collection of roots.
Splitting the Sentence
The sentence is divided into individual tokens using the default whitespace delimiter.
for word in sentence.split():
This approach respects any amount of spaces, tabs, or newline characters between words. It also means that punctuation attached to a token remains part of the token, allowing the algorithm to treat it uniformly without additional parsing.
Incremental Prefix Construction
For each token, the code builds a candidate prefix one character at a time. The variable current accumulates characters, and after each addition the algorithm checks whether the accumulated string exists in the root set.
found = False
current = ""
for c in word:
current += c
if current in roots:
result.append(current)
found = True
break
The moment a match is identified, the inner loop exits, guaranteeing that the first (and therefore shortest) root is selected. This early-exit strategy prevents unnecessary character processing once a valid replacement is known.
Handling Words Without a Matching Root
If the inner loop completes without locating a root, the original word is retained.
if not found:
result.append(word)
This branch ensures that words lacking any dictionary prefix remain unchanged in the final output, preserving the original sentence structure for those cases.
Aggregating the Result
All selected tokens-whether replaced roots or original words-are stored in a list. After processing the entire sentence, the list is joined with single spaces to produce the final string.
return " ".join(result)
Collecting tokens in a list before joining avoids repeated string concatenation, which would otherwise generate many intermediate string objects and degrade performance.
Edge-Case Considerations
The implementation gracefully handles an empty dictionary; the set conversion yields an empty set, causing every word to fall through to the “not found” branch and be emitted unchanged. An empty sentence results in sentence.split() producing an empty iterator, so the outer loop never executes and the function returns an empty string. Words that contain no characters from any root are also left untouched, as the inner loop never triggers a match. Because the split operation treats any whitespace uniformly, leading, trailing, or multiple consecutive spaces are collapsed into single delimiters, and the final join restores a single space between tokens, yielding a cleanly formatted result.
Performance Optimizations Observed
The code’s primary optimization is the use of a hash set for root lookups, which eliminates the need for linear scans through the dictionary for each word. Incremental prefix building means that each character of a word is examined at most once, and the moment a matching root appears, the inner loop stops, avoiding further unnecessary character checks. Storing intermediate results in a list and performing a single join operation at the end reduces the overhead associated with repeated string concatenation. Together, these choices keep the execution efficient even when processing long sentences or large dictionaries.
ELI5 - Simplified Explanation
Imagine you have a big box of special building blocks called roots. Each block has a magic word written on it. Now, you have a whole sentence made out of long, complicated words, and your job is to make them shorter using your special blocks.
You go through the sentence one word at a time, looking at each letter carefully. As you add letters one by one to form a little piece of the word, you check your box of special blocks to see if that piece is already there. If you find a match, you stop right away and keep just that small, magical piece. That little block replaces the long word because it is much simpler.
If you check every possible piece of the long word and none of them are in your magic box, then you just keep the original long word exactly the way it started. After checking every single word in the sentence, you glue all these pieces back together into one neat, new sentence. Every word is now either as short as a magic block or exactly as it was before.
Code Quality
Complexity Analysis
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
Other Solutions
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++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | Rust | Python | Go | TS | |||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | black-shadows | C++ | |||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| wisdompeak | 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++ | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 208: Implement Trie (Prefix Tree)
Solved On The Same Day
- problem 112: Path Sum
- problem 409: Longest Palindrome
- problem 645: Set Mismatch
- problem 717: 1-bit and 2-bit Characters
- problem 2535: Difference Between Element Sum and Digit Sum of an Array
- problem 16: 3Sum Closest
- problem 24: Swap Nodes in Pairs
- problem 113: Path Sum II
- problem 114: Flatten Binary Tree to Linked List
- problem 116: Populating Next Right Pointers in Each Node
- problem 129: Sum Root to Leaf Numbers
- problem 131: Palindrome Partitioning
- problem 137: Single Number II
- problem 162: Find Peak Element
- problem 165: Compare Version Numbers
- problem 172: Factorial Trailing Zeroes
- problem 201: Bitwise AND of Numbers Range
- problem 204: Count Primes
- problem 402: Remove K Digits
- problem 430: Flatten a Multilevel Doubly Linked List
- problem 451: Sort Characters By Frequency
- problem 539: Minimum Time Difference
- problem 583: Delete Operation for Two Strings
- problem 633: Sum of Square Numbers
- problem 650: 2 Keys Keyboard
- problem 670: Maximum Swap
- problem 786: K-th Smallest Prime Fraction
- problem 2507: Smallest Value After Replacing With Sum of Prime Factors
- problem 2523: Closest Prime Numbers in Range
Extra
- 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