Check If a Word Occurs As a Prefix of Any Word in a Sentence - 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. If searchWord is a prefix of more than one word, return the index of the first word (minimum index). If there is no such word return -1.

A prefix of a string s is any leading contiguous substring of s.

Input & Output

Example 1 — Basic Prefix Match
$ Input: sentence = "i love eating burger", searchWord = "burg"
Output: 4
💡 Note: "burg" is a prefix of "burger" which is the 4th word in the sentence
Example 2 — First Match
$ Input: sentence = "this problem is an easy problem", searchWord = "pro"
Output: 2
💡 Note: "pro" is a prefix of "problem" which appears at positions 2 and 6, return the first occurrence at index 2
Example 3 — No Match
$ Input: sentence = "i am tired", searchWord = "you"
Output: -1
💡 Note: "you" is not a prefix of any word in "i am tired"

Constraints

  • 1 ≤ sentence.length ≤ 100
  • 1 ≤ searchWord.length ≤ 10
  • sentence consists of lowercase letters and spaces
  • sentence does not have leading or trailing spaces
  • All the words in sentence are separated by a single space

Visualization

Tap to expand
Prefix Word Search in Sentence INPUT Sentence: i 1 love 2 eating 3 burger 4 searchWord: "burg" Input Values: sentence = "i love eating burger" searchWord = "burg" Find 1-indexed position ALGORITHM STEPS 1 Split Sentence Split by space into words ["i","love","eating","burger"] 2 Iterate Words Loop through each word with index (1-indexed) 3 Check Prefix Use startsWith() method word.startsWith(searchWord) 4 Return Result Return index if match found Return -1 if no match Prefix Check Results: "i" -- X | "love" -- X "eating" -- X | "burger" -- OK FINAL RESULT Match Found at Word 4: "burger" Prefix Match: burg er Output 4 "burg" is prefix of "burger" at position 4 (1-indexed) Key Insight: The split() function divides the sentence into an array of words. Then we iterate through each word using built-in startsWith() to check if searchWord is a prefix. Return the 1-indexed position of the first match, or -1 if not found. Time: O(n*m) where n=words, m=searchWord length. TutorialsPoint - Check If a Word Occurs As a Prefix of Any Word in a Sentence | Split and Built-in Functions Approach
Asked in
Amazon 3 Facebook 2
12.0K Views
Medium Frequency
~10 min Avg. Time
445 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen