Prefix Word Finder

Easy
0/40
0 upvote
Asked in company
Standard Chartered

Problem statement

You are given a string sentence containing words separated by single spaces, and a string searchWord.

Your task is to find the first word in the sentence that has searchWord as a prefix. Return the 1-indexed position of this word.


If searchWord is a prefix of multiple words, you must return the index of the first such word. If no word in the sentence has searchWord as a prefix, return -1.


Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains the sentence string.

The second line of input contains the searchWord string.


Output Format:
Print a single integer representing the 1-indexed position of the first word that has searchWord as a prefix.

If no such word is found, print -1.


Note:
A "prefix" is a contiguous sequence of characters at the beginning of a string. For example, "app" is a prefix of "apple".
Sample Input 1:
i love eating burger
burg


Sample Output 1:
4


Explanation for Sample 1:
The sentence is split into words: ["i", "love", "eating", "burger"].
- "burg" is not a prefix of "i", "love", or "eating".
- "burg" is a prefix of "burger", which is the 4th word.


Sample Input 2:
i am tired
you


Sample Output 2:
-1


Explanation for Sample 2:
The search word "you" is not a prefix of any of the words "i", "am", or "tired".


Expected Time Complexity:
The expected time complexity is O(N*M), where N is the number of words and M is the length of the searchWord.


Constraints:
1 <= sentence.length <= 100
1 <= searchWord.length <= 10
Strings consist of lowercase English letters and spaces.

Time limit: 1 sec
Approaches (1)
Prefix Word Finder
Time Complexity
Space Complexity
Code Solution
(100% EXP penalty)
Prefix Word Finder
Full screen
Console