#1455

Check If a Word Occurs As a Prefix of Any Word in a Sentence

Easy
Two PointersStringString Matching
LeetCode ↗

Approaches

💡

Intuition

Time Space

The optimal solution leverages the same approach as brute force but is more efficient by directly checking the prefix of each word without unnecessary comparisons.

⚙️

Algorithm

3 steps
  1. 1Step 1: Split the sentence into words using spaces.
  2. 2Step 2: Iterate through each word and check if it starts with searchWord using the startsWith method.
  3. 3Step 3: Return the index (1-indexed) of the first match found. If no match is found, return -1.
solution.py10 lines
1# Full working Python code
2sentence = 'i love eating burger'
3searchWord = 'burg'
4words = sentence.split()
5for i, word in enumerate(words):
6    if word.startswith(searchWord):
7        print(i + 1)
8        break
9else:
10    print(-1)

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.