Check If Word Occurs as Prefix of Any Word in Sentence

This title was summarized by AI from the post below.

🚀 Day 28 of #100DaysOfDSA 🔹 Problem: Check If a Word Occurs As a Prefix of Any Word in a Sentence Given: A sentence A search word Return the position of the first word where searchWord is a prefix. If no such word exists, return -1. 🧠 Brute Force Approach The straightforward way: 1️⃣ Split sentence into words 2️⃣ Traverse each word 3️⃣ Check: word.startsWith(searchWord) 4️⃣ Return index of first matching word ⚠️ Drawback Using: sentence.split(" ") creates extra array space. Time Complexity: Splitting + traversing → O(n) Space Complexity: Extra space for array ⚡ Optimized Approach Instead of splitting: ✔ Traverse sentence character by character ✔ Detect word starts ✔ Check prefix directly using: startsWith() This avoids creating extra arrays 🚀 💻 Code (Java) class Solution { public int isPrefixOfWord(String sentence, String searchWord) { int space = 0; for(int i = 0; i < sentence.length(); i++) { // Check first word if(i == 0) { if(sentence.substring(i).startsWith(searchWord)) { return 1; } } // New word starts after space if(sentence.charAt(i) == ' ') { space++; if(sentence.substring(i + 1).startsWith(searchWord)) { return space + 1; } } } return -1; } } ⏱ Complexity Analysis ApproachTimeSpaceSplit + TraverseO(n)O(n)Character TraversalO(n)O(1)📌 Key Takeaways Avoid unnecessary string splitting when possible Character traversal can optimize space usage startsWith() is very useful for prefix problems 💡 Interview Insight: If interviewer asks for optimization: 👉 Try solving string problems without using split(). #DSA #Java #LeetCode #Strings #CodingChallenge #100DaysOfCode

To view or add a comment, sign in

Explore content categories