- Interview Questions
- /
- Problems
- /
- Check If a Word Occurs As a Prefix of Any Word in a Sentence
Check If a Word Occurs As a Prefix of Any Word in a Sentence
Find the first word in a sentence that starts with a given search word and return its 1-based position. A short string-scanning problem that tests careful prefix checks and indexing. Solve it below in Python or JavaScript, then read the walkthrough.
Problem
You're given a sentence made of lowercase words separated by single spaces, and a searchWord.
Return the position of the first word in sentence that has searchWord as a prefix, meaning the word begins with exactly those characters. Positions are 1-based: the first word is position 1. If no word starts with searchWord, return -1.
A word counts as a prefix match of itself, so a word equal to searchWord matches.
Example 1
- Input
- sentence = "the quick brown fox", searchWord = "qu"
- Output
- 2
"quick" is the second word and starts with "qu".
Example 2
- Input
- sentence = "she sells sea shells", searchWord = "se"
- Output
- 2
"she" starts with "sh", not "se". "sells" and "sea" both match, and "sells" comes first.
Example 3
- Input
- sentence = "hello world", searchWord = "low"
- Output
- -1
"low" appears inside "hello" but not at the start of any word.
Constraints
- 1 ≤ sentence.length ≤ 10⁴
- 1 ≤ searchWord.length ≤ 10
- sentence has lowercase letters and single spaces, with no leading or trailing spaces.
- searchWord has only lowercase letters.
Practice
Runs 15 tests in your browser. Python loads on the first run (about 6 MB, then cached). Press ⌘/Ctrl + Enter to run.
Get asked Check If a Word Occurs As a Prefix of Any Word in a Sentence in a real interview?
Interview Solver gives you a working solution live, during your actual coding interview. Invisible to screensharing.
How to solve Check If a Word Occurs As a Prefix of Any Word in a Sentence
Pattern: Split and check prefixes
There's no clever trick here: look at the words in order and return the first one that starts with searchWord. What the problem really checks is whether you get the details right: the answer is 1-based, a match must be at the start of a word rather than anywhere inside it, and a word shorter than searchWord can never match.
Splitting on spaces and using the language's built-in startsWith handles all of that. If you want to avoid building the list of words, you can scan the sentence once and only compare characters at word starts.
Approach 1: Search for the substring, then map back to a word
Search for " " + searchWord in " " + sentence and count the spaces before the match to find the word number. It works and is short, but the space counting is fiddly and easy to get off by one.
Time O(n · m) · Space O(n)
Approach 2: Split into words
- Split
sentenceon single spaces. - Walk the words with their positions and return
i + 1for the first word that starts withsearchWord. - If none match, return
-1.
startsWith stops at the first mismatch, so each word costs at most m comparisons.
Time O(n) · Space O(n) for the list of words
| Approach | Time | Space |
|---|---|---|
| Search for the substring, then map back to a word | O(n · m) | O(n) |
| Split into words | O(n) | O(n) for the list of words |
Solution code
Try the practice editor first. Both solutions pass every test above.
Check If a Word Occurs As a Prefix of Any Word in a Sentence solution in Python
def is_prefix_of_word(sentence: str, search_word: str) -> int:
for i, word in enumerate(sentence.split(" ")):
if word.startswith(search_word):
return i + 1
return -1Check If a Word Occurs As a Prefix of Any Word in a Sentence solution in JavaScript
function isPrefixOfWord(sentence, searchWord) {
const words = sentence.split(' ');
for (let i = 0; i < words.length; i++) {
if (words[i].startsWith(searchWord)) return i + 1;
}
return -1;
}Common mistakes
- Returning a 0-based index.
- Using a substring search like `includes` or `in`, which matches "low" inside "hello".
- Returning the last match or every match instead of the first.
- Comparing character by character without checking that the word is at least as long as searchWord, which reads past the end of the word.
What interviewers look for
On an easy problem, interviewers listen for edge cases more than algorithms. Name them before you code: 1-based answer, prefix not substring, word shorter than the search word, and a word exactly equal to it.
If they ask for O(1) extra space, describe a single pass with a word counter that only compares characters right after a space (or at the start), skipping the rest of a word as soon as a character mismatches.
Follow-up questions
How would you answer many prefix queries against the same sentence?
Build a trie of the words once, storing at each node the smallest word position that passes through it. Each query then walks at most m nodes and reads the stored position.
Can you do it without splitting the string?
Yes. Scan once with a word counter. At the start of each word, compare characters with searchWord until one differs or the word ends; on a full match return the counter, otherwise skip to the next space.
What if words could be separated by multiple spaces or punctuation?
Split on a pattern of one or more separators and drop empty pieces, or tokenize with a regular expression for runs of letters. The prefix check stays the same.
Companies that ask Check If a Word Occurs As a Prefix of Any Word in a Sentence
Check If a Word Occurs As a Prefix of Any Word in a Sentence is tagged by 98 companies in our interview dataset. The score shows how often it comes up at each company.
- Liberty Mutual100%
- Addepar100%
- The Home Depot100%
- Apptio98%
- Allegro95%
- Yelp94.2%
- Mollie93%
- Verisk92%
- Iqvia89%
- Opendoor88%
- Floqast84%
- Charles Schwab84%
- Sabre83%
- Red Ventures83%
- Hbc Digital82%
- Terumo82%
- Olympus81%
- Dataart80%
- Whoop79%
- Cimpress78%
- Yext77%
- S P Global77%
- Booz Allen Hamilton76%
- Crunchbase75%
and 74 more.
Practice next
Get live help in the real interview
Working solutions in real time during your actual interview. Invisible to screensharing.
Start Free TrialNo credit card required