Check If a Word Occurs As a Prefix of Any Word in a Sentence (LeetCode 1455): Solution and Explanation
Given a sentence and a search word, return the 1-based position of the first word in the sentence that begins with the search word, or -1 if none does.
Intuition
Splitting the sentence into words and calling startswith on each one is correct and short. It does allocate a list of words, and it hides the actual comparison work.
Only the first few letters of each word matter. A word either matches searchWord letter by letter from its first character, or it fails at some letter and is out for good.
So one scan over the sentence is enough. Keep a pointer j into searchWord. At the start of every word j is 0; each letter that equals searchWord[j] moves j forward; the first letter that differs kills the word.
Spaces reset everything for the next word. The moment j reaches the end of searchWord, the current word is the answer, and since the scan goes left to right it is the first such word.
Approach: Single scan with a resetting pointer
- Set
word = 1andj = 0. - For each character
chof the sentence: if it is a space, incrementwordand setj = 0. - Otherwise, if
j >= 0andch == searchWord[j], incrementj; ifjnow equalslen(searchWord), returnword. - If
j >= 0and the characters differ, setj = -1so the rest of this word is ignored. - After the loop, return -1.
Step-by-step example
sentence = "i love eating burger", searchWord = "burg"
- Word 1 "i": 'i' is not 'b', so j = -1. The space moves to word 2 with j = 0.
- Word 2 "love": 'l' is not 'b', so the word fails and 'o', 'v', 'e' are skipped.
- Word 3 "eating": 'e' is not 'b', so it fails too.
- Word 4 "burger": 'b', 'u', 'r', 'g' match searchWord one by one and j reaches 4.
- j equals len("burg"), so the function returns 4.
Code: Python, Java, C++
1class Solution:
2 def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
3 word = 1
4 j = 0
5 for ch in sentence:
6 if ch == " ":
7 word += 1
8 j = 0
9 elif j >= 0:
10 if ch == searchWord[j]:
11 j += 1
12 if j == len(searchWord):
13 return word
14 else:
15 j = -1
16 return -11class Solution {
2 public int isPrefixOfWord(String sentence, String searchWord) {
3 int word = 1;
4 int j = 0;
5 for (int i = 0; i < sentence.length(); i++) {
6 char ch = sentence.charAt(i);
7 if (ch == ' ') {
8 word++;
9 j = 0;
10 } else if (j >= 0) {
11 if (ch == searchWord.charAt(j)) {
12 j++;
13 if (j == searchWord.length()) {
14 return word;
15 }
16 } else {
17 j = -1;
18 }
19 }
20 }
21 return -1;
22 }
23}1class Solution {
2public:
3 int isPrefixOfWord(string sentence, string searchWord) {
4 int word = 1;
5 int j = 0;
6 for (char ch : sentence) {
7 if (ch == ' ') {
8 word++;
9 j = 0;
10 } else if (j >= 0) {
11 if (ch == searchWord[j]) {
12 j++;
13 if (j == (int)searchWord.size()) {
14 return word;
15 }
16 } else {
17 j = -1;
18 }
19 }
20 }
21 return -1;
22 }
23};Time and space complexity
O(n)
Each character of the sentence is looked at once, and each comparison is constant time.
O(1)
Only the counters word and j are stored; no word list is built.
Other approaches
Split and startswith (time O(n), space O(n))
Split the sentence on spaces and return the first index whose word starts with searchWord. It is the clearest code, at the cost of storing all words.
Search for " " + searchWord (time O(n * m), space O(n))
Prepend a space to the sentence and look for the substring " " + searchWord, then count the spaces before the hit. It works, but counting the word number afterwards is easy to get wrong.
Common mistakes
- Accepting a match in the middle of a word, for example "ell" inside "hello". Matching must start at the first letter of a word.
- Returning a 0-based index. The problem counts words from 1.
- Not resetting the pointer at a space, so a partial match from one word carries over into the next.
- Reading past the end of searchWord when a word is longer than it; return as soon as all letters have matched.
Frequently asked questions
What should be returned if several words start with searchWord?
The position of the first one. A left-to-right scan that returns on the first full match gives exactly that.
Does searchWord count as a prefix of itself?
Yes. A word equal to searchWord starts with searchWord, so it is a valid answer.
Why use j = -1 instead of a separate flag?
It keeps the state to one variable: j >= 0 means the word is still a candidate and j says how much of searchWord it has matched, while -1 means the word already failed.