Skip to content
← All posts

Check If a Word Occurs As a Prefix: String Scanning

4 min read
leetcodeproblemeasystrings

Given a sentence consisting of words separated by spaces and a string searchWord, return the 1-indexed position of the first word in sentence that starts with searchWord as a prefix. If no word matches, return -1.

This is LeetCode 1455: Check If a Word Occurs As a Prefix of Any Word in a Sentence, and it is a clean exercise in splitting a string and checking prefixes. The problem is simple, but it drills two fundamental string operations that show up in harder problems.

searchWord = "burg"word 1iword 2loveword 3eatingword 4burgerMatch at position 4
sentence = "i love eating burger", searchWord = "burg". Word 4 ("burger") starts with "burg". Return 4.

The key insight

Split the sentence into words, then iterate through them. For each word, check if it starts with searchWord. The moment you find a match, return the 1-indexed position. If you reach the end without a match, return -1.

Python's str.startswith() method handles the prefix check in one call. You do not need to manually compare characters. The split-and-scan pattern is the entire solution.

The solution

def is_prefix_of_word(sentence: str, search_word: str) -> int:
    for i, word in enumerate(sentence.split(), 1):
        if word.startswith(search_word):
            return i
    return -1

The enumerate(sentence.split(), 1) call splits the sentence into words and pairs each word with a 1-based index. For each word, startswith checks whether the word begins with search_word. If it does, we return the index immediately. If no word matches after the full scan, we return -1.

The 1 argument to enumerate is the starting index. This avoids the off-by-one error of having to add 1 to a 0-based index, which is exactly the kind of small mistake that costs time in an interview.

Python's str.startswith() runs in O(k) time where k is the length of the prefix. It is the cleanest way to check prefixes. For multiple prefix checks against the same set of words, a trie would be faster, but for a single check per word, startswith is the right tool.

Visual walkthrough

Let's trace through a second example: sentence = "this problem is an easy problem", searchWord = "pro". Watch how we check each word from left to right and stop at the first match.

Step 1: Check word 1 "this". Does it start with "pro"?

searchWord = "pro"word 1thisword 2problemword 3isword 4anword 5easyword 6problem

"this" does not start with "pro". Move to the next word.

Step 2: Check word 2 "problem". Does it start with "pro"?

searchWord = "pro"word 1thisword 2problemword 3isword 4anword 5easyword 6problem

"problem" starts with "pro". We found a match at position 2. Return 2.

Result: Return 2

searchWord = "pro"word 1thisword 2problemword 3isword 4anword 5easyword 6problem

Word 2 ("problem") is the first word that starts with "pro". We stop immediately and return 2. We never need to check words 3 through 6.

We check "this" first. It does not start with "pro", so we move on. The second word "problem" starts with "pro", so we immediately return 2. We never even look at words 3 through 6. This early exit is built into the linear scan.

Complexity analysis

ApproachTimeSpace
Linear scanO(n)O(n)

Time is O(n) where n is the length of the sentence. The split() call processes every character once. The startswith checks in the worst case also examine every character (if no word matches and all prefix checks fail). Total work is proportional to the sentence length.

Space is O(n) because split() creates a list of words. In the worst case, the list contains n/2 single-character words. You could avoid this by scanning the sentence character by character and tracking word boundaries, but the split approach is simpler and the space cost is negligible for interview purposes.

The building blocks

1. String splitting

Splitting a string by a delimiter is one of the most common string operations. Python's str.split() with no arguments splits on whitespace and handles multiple spaces gracefully.

words = sentence.split()

This pattern appears in many string problems: reverse words in a string, count word frequencies, parse CSV data. The key detail is that split() without arguments strips leading and trailing whitespace and collapses multiple spaces into one, while split(' ') does not.

2. Prefix checking with startswith

Checking whether one string is a prefix of another is a fundamental operation. Python gives you startswith as a built-in method.

if word.startswith(prefix):
    return True

Under the hood, startswith compares characters from the beginning of both strings. It returns as soon as it finds a mismatch or reaches the end of the prefix. This is the same logic you would write manually, but packaged into a single readable call.

Edge cases

  • searchWord longer than every word: no word can start with a prefix longer than itself. startswith handles this correctly, returning False when the prefix is longer than the word.
  • Exact match: if a word equals searchWord exactly, startswith returns True. The word "pro" starts with "pro".
  • Multiple matches: return only the first match. The early return in the loop guarantees this.
  • Single word sentence: the sentence has no spaces. split() returns a list with one element. If that word starts with searchWord, return 1. Otherwise, return -1.
  • searchWord is empty: an empty string is a prefix of every string. "anything".startswith("") returns True. The problem guarantees searchWord has at least one character, but it is worth knowing how startswith behaves.

From understanding to recall

You have seen how split-and-scan solves this problem in three lines. The logic is simple. But under interview pressure, the details matter. Do you use enumerate starting at 0 or 1? Do you call startswith or try to slice the string manually? Do you return the index or the word?

These are not conceptual questions. They are recall questions. Spaced repetition makes the answers automatic. You practice writing the split, the enumerate with a start index, and the startswith check from scratch at increasing intervals. After a few rounds, the pattern flows out without hesitation.

Related posts

CodeBricks breaks Check If a Word Occurs As a Prefix into its string-splitting and prefix-checking building blocks, then drills them independently with spaced repetition. You type each piece from scratch until the pattern is automatic. When a string prefix problem shows up in your interview, you do not hesitate. You just write it.