Problem 648

Abstract / Summary

Given a list of words and a root dictionary replace each word with the shortest root prefix if possible

Note

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

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)
18 lines | 539 bytes | submitted August 15, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 69% (400k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • String
  • Trie
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 “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.

written by openai gpt

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.

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 = 7 | μ = 7.07 | σ = 0.81

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++ 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++
37 links | 23 authors | 10 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

30 solutions   August 15, 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