🚀 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
Check If Word Occurs as Prefix of Any Word in Sentence
More Relevant Posts
-
🚀 Day 29 of #100DaysOfDSA 🔹 Problem: Append Characters to String to Make Subsequence Given two strings s and t, return the minimum number of characters that need to be appended to the end of s so that tbecomes a subsequence of s. 🧠 Brute Force Approach The naive way could be: 1️⃣ Try appending characters one by one 2️⃣ After every append: Check whether t becomes subsequence of s ❌ Why Brute Force is Inefficient? Checking subsequence repeatedly becomes costly. Time Complexity can grow significantly for large strings. ⚡ Optimized Two Pointer Approach Instead of modifying the string: ✔ Traverse both strings together ✔ Match characters sequentially 🔥 Core Idea Use: i → pointer for s j → pointer for t If characters match: s.charAt(i) == t.charAt(j) Move both pointers. Otherwise: Move only i At the end: ✔ Remaining unmatched characters in t are the answer. 💻 Code (Java) class Solution { public int appendCharacters(String s, String t) { int i = 0, j = 0; while (i < s.length() && j < t.length()) { if (s.charAt(i) == t.charAt(j)) { j++; } i++; } return t.length() - j; } } 🧠 Why Does This Work? If: j = matched characters in t Then: t.length() - j represents remaining characters still needed. ⏱ Complexity Analysis ApproachTimeSpaceBrute ForceHigherO(1)Two PointerO(n + m)O(1) ✔ Efficient and clean solution 🚀 📌 Key Takeaways Two pointers are very powerful for subsequence problems No need to actually append characters Think in terms of matching progress 💡 Interview Insight: Whenever you hear: 👉 “subsequence” Think: Relative order matters Two pointers may help #DSA #Java #LeetCode #TwoPointers #Strings #CodingChallenge #100DaysOfCode
To view or add a comment, sign in
-
Binary search on a sorted array is easy. Binary search on a rotated sorted array is where it gets interesting. Day 36 of #100DaysOfCode Today I solved LeetCode 33 - Search in Rotated Sorted Array, and this is one of those problems that every developer preparing for interviews must know. The problem: A sorted array has been rotated at some unknown pivot. Given a target, find its index in O(log n) time or return -1. How I approached it: The key observation is that even after rotation, at least one half of the array is always perfectly sorted. I used this fact to decide which half to search. At every step I calculated mid and checked two things. First, if nums[low] <= nums[mid], the left half is sorted. In that case if target lies within nums[low] and nums[mid], I searched left, otherwise I moved to the right half. If the left half is not sorted, the right half must be sorted. Then if target lies within nums[mid] and nums[high], I searched right, otherwise I moved to the left half. This gives a clean O(log n) solution with no extra space. What I learned from this problem: The real insight here is not binary search itself, it is knowing which half is still sorted at every step. Once you identify the sorted half, the rest of the logic is exactly like standard binary search. This problem teaches you to extract useful information from partial structure in data, which is a skill that goes far beyond just this one problem. 0ms runtime beating 100% was a great result today. #100DaysOfCode #LeetCode #DSA #Java #BinarySearch #Programming #SoftwareEngineering #CodingChallenge #InterviewPrep
To view or add a comment, sign in
-
-
📅 Date: May 4, 2026 Day 10 of my LeetCode Journey 🚀 ✅ Problem Solved: 21. Merge Two Sorted Lists 🧠 Approach & Smart Solution: Hitting double digits on my streak today! To solve this foundational linked list problem, I opted for a highly elegant Recursive Approach instead of a traditional iterative while-loop. Since both linked lists are already sorted, we can simply compare their current head nodes and recursively build the rest of the list. • Pseudo-code: Check if both lists are not null. Compare the values of the current nodes of list1 and list2. If list1's value is smaller, set list1.next to the recursive result of the rest of list1 and list2. Return list1. If list2's value is smaller (or equal), set list2.next to the recursive result of list1 and the rest of list2. Return list2. Handle Base Cases: If the loop exits because one list is null, simply return the other non-null list to append the remaining elements. This concise recursive logic eliminates the need for dummy nodes and extra pointer variables, keeping the code incredibly clean! ⏱️ Time Complexity: O(n + m) (Where 'n' and 'm' are the lengths of the two lists, as we visit each node exactly once) 📦 Space Complexity: O(n + m) (Due to the recursion call stack depth) 📊 Progress Update: • Streak: 10 Days 🔥 • Difficulty: Easy • Pattern: Linked List / Recursion 🔗 LeetCode Profile: https://lnkd.in/gBcDQwtb (@Hari312004) Reaching Day 10! Recursion continues to prove itself as one of the most powerful tools for linked list manipulation! 💡 #LeetCode #DSA #LinkedLists #Java #Recursion #CodingJourney #ProblemSolving #InterviewPrep #Consistency #BackendDevelopment
To view or add a comment, sign in
-
-
𝐃𝐚𝐲 𝟏𝟑𝟎/𝟑𝟔𝟓 🚀 📌 𝐋𝐞𝐞𝐭𝐂𝐨𝐝𝐞 𝐏𝐎𝐓𝐃: 𝐋𝐨𝐧𝐠𝐞𝐬𝐭 𝐂𝐨𝐦𝐦𝐨𝐧 𝐒𝐮𝐟𝐟𝐢𝐱 𝐐𝐮𝐞𝐫𝐢𝐞𝐬 🔎 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡: • Build a Trie using reversed words from wordsContainer • Each Trie node stores: - shortest word length - corresponding smallest index • Traverse query strings in reverse order • Follow longest matching suffix path in Trie • Return best matching index stored at deepest valid node 🔍 𝐀𝐥𝐠𝐨𝐫𝐢𝐭𝐡𝐦: • Trie + String Processing ⏱ 𝐓𝐢𝐦𝐞 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲: • O(total characters in wordsContainer + wordsQuery) 🧠 𝐒𝐩𝐚𝐜𝐞 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲: • O(total characters in Trie) 📈 𝐊𝐞𝐲 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲: • Reversing strings transforms suffix problems into prefix matching problems 🔗 Problem Link: https://lnkd.in/dXYjF78v #LeetCode #LeetcodePOTD #365DaysOfCode #DSA #Java #Trie #Strings #ProblemSolving
To view or add a comment, sign in
-
-
📅 Date: May 8, 2026 Day 12 of my LeetCode Journey 🚀 ✅ Problem Solved: 27. Remove Element 🧠 Approach & Smart Solution: Continuing to strengthen my core fundamentals with array manipulation! This problem requires removing all instances of a specific value from an array, but with a strict constraint: it must be done in-place with O(1) extra memory. To achieve this, I used a highly efficient Two-Pointer technique. • Pseudo-code: Initialize an 'index' pointer at 0 to track the position for valid elements. Iterate through the array with a loop variable 'i'. If the current element nums[i] is NOT equal to the target value to remove: Place nums[i] at the nums[index] position. Increment the 'index' by 1. Return the 'index', which now represents the new length of the modified array. By overwriting the unwanted values directly, we avoid creating any new arrays and keep the code running at optimal speed! ⏱️ Time Complexity: O(n) (Single pass through the array) 📦 Space Complexity: O(1) (In-place modification, zero extra memory) 📊 Progress Update: • Streak: 10 Days 🔥 • Difficulty: Easy • Pattern: Arrays / Two Pointers / In-place Modification 🔗 LeetCode Profile: https://lnkd.in/gBcDQwtb (@Hari312004) Mastering in-place array operations is a critical skill for writing clean, optimized backend code! 💡 #LeetCode #DSA #Arrays #TwoPointers #Java #CodingJourney #ProblemSolving #InterviewPrep #Consistency #BackendDevelopment
To view or add a comment, sign in
-
-
✳️Day 51 of #100DaysOfCode✳️ 🚀 Cracking the Sliding Window: LeetCode 1004 (Max Consecutive Ones III) I recently tackled this popular interview question using an efficient Sliding Window approach in Java. 🔹The challenge: Find the maximum number of consecutive 1s in a binary array if you can flip at most k 0s. ⭐Here is the step-by-step breakdown of how my solution works: 🔸Initialize Two Pointers: Use a fast pointer (j) to expand the window and a slow pointer (i) to contract it, keeping track of the maxLen and the number of zeroes encountered. 🔸Expand the Window: Iterate through the array with j. If nums[j] == 0, increment the zero counter. 🔹Shrink When Invalid: If the number of zeros exceeds k, move the left pointer i forward. If the element leaving the window (nums[i]) is a 0, decrement the zero counter. 🔹Update Max Length: At each step, calculate the valid window size using j - i + 1 and update the maximum length found so far. 🔹Complexity: Time Complexity: O(N) – Each element is visited at most twice. Space Complexity: O(1) – Optimal memory usage with no extra data structures. Always satisfying to see all test cases pass with clean, readable code! 💻✨ #LeetCode #Java #DataStructures #Algorithms #SlidingWindow #CodingLife #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Day 26 of #100DaysOfDSA 🔹 Problem: K Closest Points to Origin Given an array of points on a 2D plane, return the k closest points to the origin (0,0). 🧠 Brute Force Approach (First Thought) The most intuitive way: Compute distance of each point from origin 👉 Use: x² + y² (no need for square root) Sort all points based on distance Pick first k points ✔ Time Complexity: Distance calc → O(n) Sorting → O(n log n) ✔ Overall: O(n log n) 👉 Drawback: We sort the entire array even when we only need k points ⚡ Optimized Approach (Max Heap) Instead of sorting everything, we can use a Max Heap of size k: ✔ Idea: Keep only k closest points in heap If heap size exceeds k → remove farthest point ✔ This ensures: Heap always contains best candidates ✔ Time Complexity: Heap operations → O(n log k) ✔ Much better when k << n 💻 Code (Java) class Solution { private int getDistance(int[] point) { return point[0] * point[0] + point[1] * point[1]; } public int[][] kClosest(int[][] points, int k) { PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> getDistance(b) - getDistance(a)); for (int[] point : points) { pq.add(point); if (pq.size() > k) pq.poll(); } int[][] ans = new int[k][2]; for (int i = 0; i < k; i++) { ans[i] = pq.poll(); } return ans; } } 📌 Key Takeaways Always question: Do I really need full sorting? Heap is powerful for Top K problems Avoid unnecessary computations (no sqrt needed!) 💡 Interview Tip: Mention both brute force (sorting) and optimized (heap) — shows depth of thinking. #DSA #Java #LeetCode #Heap #CodingChallenge #100DaysOfCode
To view or add a comment, sign in
-
Today I solved LeetCode #39 – Combination Sum (🟡 Medium) 🧠 Problem Summary Given an array of distinct integers (candidates) and a target value, we need to find all unique combinations where the chosen numbers sum to the target. 👉 We can use the same number multiple times. 💡 My Approach (Step-by-Step) 1️⃣ I used Recursion + Backtracking Because we need to explore all possible combinations 2️⃣ I created a function: recur(target, candidates, start) 3️⃣ Base Case If target == 0 👉 I found one valid combination 👉 Add it to the answer list 4️⃣ Loop through candidates Start from start index to avoid duplicates 5️⃣ Choose element Add element to current list 6️⃣ Recursive Call Reduce target: target - candidates[i] Pass same index i (because reuse is allowed) 7️⃣ Backtracking Remove last element 👉 This helps explore new combinations 🔁 Example Flow Target = 8, candidates = [2,3,5] 2 → 2 → 2 → 2 → ✅ (sum = 8) 3 → 5 → ✅ …and more combinations explored recursively ⏱️ Time Complexity Approximately O(2^target) (since we explore combinations) 📌 Key Learning Backtracking is powerful when we need all possible combinations Important to undo choices (backtrack) after recursion 💻 Code I Implemented (Used Java with recursion and backtracking) Feeling happy to improve my problem-solving skills step by step 💪 Consistency is the key 🔑 #DSA #LeetCode #Java #CodingJourney #Backtracking #ProblemSolving
To view or add a comment, sign in
-
-
Today I tackled the Sequence Equation problem, which involves working with permutations and index mapping. 🔍 Problem Insight: Given a permutation p, find values of y such that: 👉 p[p[y]] = x for all x from 1 to n 💡 Key Idea: Instead of brute force, I used: Position mapping for fast lookup Double indexing trick (pos[pos[x]]) 🚀 Why this works: It reduces complexity from O(n²) to O(n), making it highly efficient. 🧠 What I learned: Importance of inverse mapping Optimizing lookup operations Writing clean and efficient Java code 📌 Example: Input: [5, 2, 1, 3, 4] Output: [4, 2, 5, 1, 3] 🔖 Tags #Java #DataStructures #Algorithms #CodingChallenge #ProblemSolving #100DaysOfCode #DeveloperJourney #SoftwareDeveloper #Hackerrank #CodingPractice #TechLearning
To view or add a comment, sign in
-
-
This is not just a Hard problem. This is one of the hardest Hard problems on LeetCode. Day 44 of #100DaysOfCode Today I solved LeetCode 10 - Regular Expression Matching. Hard difficulty. 354 out of 354 test cases passed. The problem: Given a string s and a pattern p, implement regex matching that supports two special characters. A dot matches any single character. An asterisk matches zero or more of the preceding element. The match must cover the entire string. The approach: This is a classic 2D dynamic programming problem. I created a boolean dp table of size (m+1) x (n+1) where dp[i][j] represents whether the first i characters of s match the first j characters of p. Base case: dp[0][0] is true since an empty string matches an empty pattern. For patterns like a* or a*b*, these can match an empty string so I pre-filled the first row accordingly. For each cell, if the current pattern character matches the current string character or is a dot, dp[i][j] inherits from dp[i-1][j-1]. If the pattern character is an asterisk, it can either act as zero occurrences of the preceding character, which means looking at dp[i][j-2], or as one or more occurrences if the preceding pattern character matches the current string character. What I learned: Regex matching is the kind of problem where brute force and recursion feel natural but fail on edge cases. Dynamic programming forces you to think about every state systematically. The asterisk case is where most people get stuck and it is all about understanding that star means zero or more, not one or more. This problem is frequently asked at top product companies. Solving it clean feels like a real milestone. Day 44 done. Streak alive. #100DaysOfCode #LeetCode #DSA #Java #DynamicProgramming #Programming #SoftwareEngineering #CodingChallenge #Hard #InterviewPrep
To view or add a comment, sign in
-