Python 1455.py
class Solution:
def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
for i, w in enumerate(sentence.split(), 1):
if w.startswith(searchWord):
return i
return -1
Difficulty
and has an acceptance rate of about 69% (300k+ submissions).
Typical patterns to solve this problem:
- String
- String Matching
- Two Pointers
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 defines a class Solution with a single method isPrefixOfWord. The method receives a sentence and a search word, both as strings, and determines the position (1-based) of the first word in the sentence that begins with the given search word. If no such word exists, the method returns -1. The algorithm proceeds by splitting the sentence into individual words, iterating through them while maintaining a counter, and checking each word for the required prefix condition.
Core Logic
The central operation is the iteration over the words obtained from the sentence. The code uses Python’s str.split() method without arguments, which splits on any whitespace and discards empty substrings. The enumeration starts at 1 to align the index with the problem’s 1-based requirement.
for i, w in enumerate(sentence.split(), 1):
if w.startswith(searchWord):
return i
When a word w satisfies w.startswith(searchWord), the current index i is immediately returned, terminating the search. If the loop completes without finding a match, the method falls back to a sentinel return value:
return -1
Edge Cases Handled
The implementation gracefully handles several edge conditions:
- Empty sentence -
sentence.split()yields an empty list, causing the loop body to be skipped and the method to return-1. - Empty search word -
str.startswith('')is defined to beTruefor any string, so the first word of the sentence (if any) will be considered a match, and the method returns1. - Multiple consecutive spaces -
split()treats any amount of whitespace as a delimiter, so extra spaces do not produce empty tokens and do not affect the index counting. - Search word longer than any sentence word -
startswithwill evaluate toFalsefor all words, leading to the final-1return. - Sentence containing only whitespace - after splitting, the resulting list is empty, and the method returns
-1.
Performance Optimizations
The code exhibits a few implicit optimizations:
- Early exit on first match - By returning as soon as a matching prefix is found, the method avoids unnecessary processing of the remaining words.
- Built-in string operations - Leveraging
str.split()andstr.startswith()utilizes highly optimized C-level implementations within the Python runtime, providing faster execution than manual parsing or character-by-character comparison. - Enumeration with start index - Using
enumerate(..., 1)eliminates the need for a separate counter variable and an additional increment operation, streamlining the loop construct.
ELI5 - Simplified Explanation
Imagine you have a long train of toy cars lined up on the rug. Each car has a little word written on its roof. You are looking for a specific sticker that starts your favorite word.
This code acts like a helper who looks at each car in the line one by one, starting from the very first car in the row. As the helper looks at each car, they count how far along the line they are.
If the word on the car starts with the special letters you are looking for, the helper points to that car and shouts out which number it is in the line.
If the helper checks every single car and none of them start with those letters, the helper gives up and tells you that the word is not hiding in the train at all.
Code Quality
Complexity Analysis
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++ | Python | Java | TS | ||||||||
| WalkCCC | Python | ||||||||||||
| leetcode.ca | C++ | Python | Java | Go | PHP | Rust | TS | ||||||
| Progiez | C++ | Python | Java | ||||||||||
| github | BigEggStudy | C# | |||||||||||
| black-shadows | C++ | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| DimitrisJim | C | ||||||||||||
| fartem | Ruby | ||||||||||||
| fsq | C++ | ||||||||||||
| halfrost | Go | ||||||||||||
| JoshCrozier | JS | ||||||||||||
| Krazune | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| lzl124631x | C++ | ||||||||||||
| Shamik07 | Dart | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||||
| WalkCCC | Python | ||||||||||||
| leetcode.ca | C++, Go, Java, PHP, Python, Rust, TypeScript | ||||||||||||
| Progiez | C++, Java, Python | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++, C++ | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| DimitrisJim | C | ||||||||||||
| fartem | Ruby | ||||||||||||
| fsq | C++ | ||||||||||||
| halfrost | Go | ||||||||||||
| JoshCrozier | JavaScript | ||||||||||||
| Krazune | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| lzl124631x | C++ | ||||||||||||
| Shamik07 | Dart | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 2185: Counting Words With a Given Prefix
Solved On The Same Day
- problem 1021: Remove Outermost Parentheses
- problem 1544: Make The String Great
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