Check If a Word Occurs As a Prefix of Any Word in a Sentence — LeetCode 1455 Python Solution
- Problem
- #1455
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
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
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 -1Complexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n) |
| Space | O(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.