Problem 1455

Abstract / Summary

Check if any word in the sentence starts with the given word.

Note

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

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
6 lines | 227 bytes | submitted November 26, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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

Typical patterns to solve this problem:
  • String
  • String Matching
  • Two Pointers
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 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 be True for any string, so the first word of the sentence (if any) will be considered a match, and the method returns 1.
  • 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 - startswith will evaluate to False for all words, leading to the final -1 return.
  • 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() and str.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.
written by openai gpt

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.

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 = 9 | μ = 8.56 | σ = 1.31

Complexity Analysis

not analyzed yet

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 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
31 links | 20 authors | 12 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

2 easy
3 solutions   November 26, 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