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

Given a `sentence` of words separated by single spaces and a string `searchWord`, check whether `searchWord` is a prefix of any word in `sentence`. Return the 1-indexed position of the first such word, or `-1` if there is none. A prefix of a string is any leading contiguous substring of it.

30:00

Check If a Word Occurs As a Prefix of Any Word in a Sentence
easy
Free written solution
Topics
Companies

Given a sentence of words separated by single spaces and a string searchWord, check whether searchWord is a prefix of any word in sentence. Return the 1-indexed position of the first such word, or -1 if there is none. A prefix of a string is any leading contiguous substring of it.

Example 1:
Input: {"sentence":"i love eating burger","searchWord":"burg"}
Output: 4
Constraints:
  • 1≤sentence.length≤1001 \leq \text{sentence.length} \leq 100

  • 1≤searchWord.length≤101 \leq \text{searchWord.length} \leq 10

  • sentence consists of lowercase English letters and spaces.

  • searchWord consists of lowercase English letters.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"sentence":"i love eating burger","searchWord":"burg"}

word = 1 counts which word we are in, and j = 0 points at the next letter of "burg" that the current word must match.

searchWord, j marks the next letter to match

b

▲j

u

1

r

2

g

3

sentence, one block per word

i

word 1

l
o
v
e

word 2

e
a
t
i
n
g

word 3

b
u
r
g
e
r

word 4

word = 1
j = 0
i = -
word starts at 0
Variables
VariableValue
word1
j0
DepthFunction Call
Stack empty
0/14