DDSA Solutions

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

Time: O(n·m)
Space: O(n)
Advertisement

Intuition

Find first word in sentence where the prefix is a prefix of that word. Simple string split and check.

Algorithm

  1. 1Split sentence into words.
  2. 2For each word: check if it starts with the given prefix.
  3. 3Return 1-indexed position of first match, or -1.

Common Pitfalls

  • 1-indexed output. Check StartsWith or substring[0..prefix.length-1] == prefix.
1455.cs
C#
// Approach: Split sentence into words; return 1-indexed position of first word that starts with searchWord.
// Time: O(n·m) Space: O(n)

public class Solution
{
    public int IsPrefixOfWord(string sentence, string searchWord)
    {
        string[] words = sentence.Split(' ');

        for (int i = 0; i < words.Length; i++)
        {
            if (words[i].StartsWith(searchWord))
                return i + 1;
        }

        return -1;
    }
}
Advertisement
Was this solution helpful?