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

EasyStringstwo pointers

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given a sentence made of words separated by single spaces, and a string searchWord. Find the first word in the sentence that starts with searchWord (a word counts even if it is exactly equal to searchWord). Return its position using **1-based** indexing. If several words qualify, return the smallest position; if none do, return -1.

Examples

Input: sentence = "we love coding love", searchWord = "lo"
Output: 2
Both "love" words start with "lo"; the first one is word 2.
Input: sentence = "hello world", searchWord = "orl"
Output: -1
"orl" appears inside "world" but is not a prefix of any word.
Input: sentence = "pin pine", searchWord = "pine"
Output: 2
"pin" is shorter than "pine", so only word 2 matches.

Constraints

  • 1 <= sentence.length <= 100
  • 1 <= searchWord.length <= 10
  • `sentence` and `searchWord` contain only lowercase English letters, and `sentence` also contains single spaces
  • `sentence` has no leading or trailing spaces

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More two pointers problems