Check If a Word Occurs As a Prefix of Any Word in a Sentence — LeetCode 1455 Python Solution

EasyTwo PointersStringString Matching
Problem
#1455
Reading time
2 min

The problem

Given a sentence that consists of some words separated by a single space, and a searchWord, check if searchWord is a prefix of any word in sentence. Return the index of the word in sentence (1-indexed) where searchWord is a prefix of this word.

Example

Input
sentence = "i love eating burger", searchWord = "burg"
Output
4
Explanation
"burg" is prefix of "burger" which is the 4th word in the sentence.

Python solution

Python
class Solution:
    def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
        for i, s in enumerate(sentence.split(), 1):
            if s.startswith(searchWord):
                return i
        return -1

Complexity

MeasureComplexity
TimeO(m \times n)
SpaceO(m) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence?
LeetCode 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence is rated Easy on LeetCode.
What is the time complexity of LeetCode 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence?
The Python solution on this page uses O(m) auxiliary space.
What topics does LeetCode 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence cover?
LeetCode 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence is tagged Two Pointers, String and String Matching on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview