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
Solving LeetCode 33 - Search in Rotated Sorted Array in O(log n) time
More Relevant Posts
-
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
-
-
🚀 Day 62: Foundations of Sorting — Bubble vs. Selection Logic 🔢 I’m 62 days into my Java journey, and today was all about order. I stepped into the world of Sorting Algorithms, exploring the mechanics of how we organize "jumbled" data into a structured sequence. 1. Bubble Sort (The "Rising" Logic) 🫧 ▫️ The Logic: It works by repeatedly stepping through the list, comparing adjacent elements and swapping them if they are in the wrong order. Why it's called Bubble? Because the largest elements "bubble up" to the end of the array with each pass. ▫️ Efficiency: While simple to implement, its (O(n^2)) time complexity makes it best for small datasets or nearly sorted lists. 2. Selection Sort (The "Minimum" Search) 🎯 ▫️ The Logic: This algorithm divides the array into a sorted and an unsorted part. It repeatedly finds the minimum element from the unsorted section and swaps it with the first element of that section. ▫️ The Advantage: Unlike Bubble Sort, it performs a maximum of (n-1) swaps, making it more efficient in terms of memory writes. ▫️ Efficiency: It also has an (O(n^2)) time complexity, but its logic is the basis for more advanced algorithms. 💡 My Key Takeaway: Sorting isn't just about the final result; it’s about understanding Swapping Logic and Nested Loop Control. These basic algorithms are the building blocks for the more complex ones I’ll be tackling next, like Quick Sort and Merge Sort. Question for the Developers: We know (O(n^2)) algorithms aren't the fastest for huge data, but which one do you find easier to explain to a beginner—Bubble or Selection? I’m finding the "Bubbling" visual very intuitive! 👇 #Java #CoreJava #SortingAlgorithms #BubbleSort #SelectionSort #100DaysOfCode #BackendDevelopment #DataStructures #LearningInPublic #CleanCode 10000 Coders Meghana M
To view or add a comment, sign in
-
“Which language should I learn?” Wrong question. I used to think learning a new language would make me better. Then I worked on systems that failed in production. The issue wasn’t: -Java vs Python -Syntax -Frameworks It was the design. We faced problems like: • Duplicate requests due to retries • Slow APIs under load • Tight coupling between services None of these can be solved by switching languages. They required: Better API design Understanding system boundaries Thinking through failure scenarios If you want to grow, focus on: • System Design • API Design • Low-Level Design (LLD) • Analytical reasoning The language we use might change. So our problem-solving skills should improve. There are well in-depth resources from Shrayansh Jain #java #systemdesign #hld
To view or add a comment, sign in
-
-
🚀 DAY 125/150 — BINARY SEARCH ON ROTATED ARRAY! 🔍📊 Day 125 of my 150 Days DSA Challenge in Java and today I solved a problem that strengthens understanding of Binary Search and sorted array observation 💻🧠 📌 Problem Solved: Find Minimum in Rotated Sorted Array 📌 LeetCode: #153 📌 Difficulty: Medium 🔹 Problem Insight We are given a sorted array that has been rotated at some pivot. 👉 Example: [4,5,6,7,0,1,2] 🎯 Goal: Find the minimum element in O(log n) time. 🔹 Approach Used I used a Binary Search approach: 🔁 Key Observation: • One half of the array is always sorted • The minimum element lies in the unsorted part ⚡ Logic: • Compare mid with right If nums[mid] > nums[right] → minimum lies on right side Else → minimum lies on left side including mid ✔️ Continue until left == right ⏱ Complexity Time Complexity: O(log n) Space Complexity: O(1) 🧠 What I Learned • Binary Search is not only for searching elements • Observing sorted and unsorted portions simplifies problems • Pattern recognition is very important in optimized solutions 💡 Key Takeaway This problem taught me: How to apply Binary Search creatively Identifying pivot behavior in rotated arrays Reducing brute force solutions to logarithmic time 🌱 Learning Insight Now I’m improving at: 👉 Solving Binary Search pattern problems 👉 Thinking in terms of optimization and observations 🚀 ✅ Day 125 completed 🚀 25 days to go 🔗 Java Solution on GitHub: 👉 https://lnkd.in/gdyaDxge 💡 The key to Binary Search is recognizing the pattern, not memorizing the code. #DSAChallenge #Java #LeetCode #BinarySearch #Arrays #Algorithms #150DaysOfCode #ProblemSolving #CodingJourney #InterviewPrep #LearningInPublic
To view or add a comment, sign in
-
-
🚀 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
-
✳️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
-
-
#CodeEveryday — My DSA Journey | Day 27 🧩 Problem Solved: Construct Binary Search Tree from Preorder Traversal (LeetCode #1008) 💭 What I Learned: Constructed a Binary Search Tree (BST) using preorder traversal by leveraging the relationship between: 👉 Preorder Traversal = Root → Left → Right 👉 Inorder Traversal of BST = Sorted Order Approach: ✔️ Created inorder traversal by sorting the preorder array ✔️ Used a HashMap to store inorder indices for fast lookup ✔️ Recursively built left and right subtrees using preorder + inorder ranges This strengthened my understanding of tree construction using traversal techniques. ⏱ Time Complexity: O(n log n) (due to sorting) 🧠 Space Complexity: O(n) ⚡ Key Takeaways: ✔️ BST inorder traversal is always sorted ✔️ Tree construction problems rely heavily on traversal properties ✔️ HashMap helps optimize inorder index lookup from O(n) → O(1) 💻 Language Used: Java ☕ 📘 Concepts: BST · Tree Construction · Recursion · Preorder Traversal · Inorder Traversal #CodeEveryday #DSA #LeetCode #Java #BST #Trees #Recursion #ProblemSolving #Algorithms #CodingJourney #Consistency 🚀
To view or add a comment, sign in
-
-
🚀 DSA Journey — LeetCode Practice 📌 Problem: Find Smallest Letter Greater Than Target 💻 Language: Java 🔹 Approach: To solve this problem, I used the Binary Search algorithm on a sorted character array. • Initialize start and end pointers • Traverse the array using Binary Search • If the current character is less than or equal to the target, move towards the right side • Otherwise, store the current character as a possible answer and move left to find a smaller valid character • Return the final stored answer 📌 Logic Insight: The goal of this problem is to find: Smallest character strictly greater than target • If: letters[mid] <= target Move right side: start = mid + 1; Because the current character cannot be the answer. • If: letters[mid] > target Store possible answer: ans = letters[mid]; Then move left side: end = mid - 1; to check whether there is a smaller valid character available. This helps in efficiently finding the next greatest character using Binary Search. 📌 Binary Search Formula: mid=start+end2mid=\frac{start+end}{2}mid=2start+end ⏱ Time Complexity: O(log n) 🧩 Space Complexity: O(1) 💡 Key Learning: This problem helped me understand how Binary Search can be applied beyond integers and used with character arrays as well. It also improved my understanding of conditions, search space reduction, and how to track potential answers during traversal. #DSA #Java #LeetCode #BinarySearch #Arrays #ProblemSolving #CodingJourney #LearningInPublic
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
-
-
🚀 Solved of all 4 problems from LeetCode Weekly Contest #501 (Easy → Hard) using Java. This contest tested my problem-solving skills across arrays, string parsing, number theory, graph algorithms, and optimization. Here’s a quick breakdown of my approach: 🔹 Q1. Concatenate Array With Reverse Approach: Used a single traversal to construct the result array efficiently. The first half stores the original elements, while the second half stores the same elements in reverse order. Code: https://lnkd.in/gfzAKbVq 🔹 Q2. Count Valid Word Occurrences Approach: Used String Parsing + HashMap. Parsed the concatenated string character by character, extracted valid words based on problem constraints, and stored frequencies for fast query lookup. Code: https://lnkd.in/g-tP4CR8 🔹 Q3. Minimize Array Sum Using Divisible Replacements Approach: Used factor enumeration + presence mapping. For each number, checked all divisors up to √n, identified the smallest valid factor present in the original array, and minimized the final sum. Code: https://lnkd.in/gxYBczeR 🔹 Q4. Minimum Cost to Buy Apples II Approach: Used Graph + Dijkstra’s Algorithm. For every city, computed the minimum travel cost and tax cost separately, then evaluated the optimal city to buy apples with minimum total cost. Code: https://lnkd.in/gv86XEKz 💡 Key takeaway: Consistency under pressure improves both coding speed and decision-making. Would love to know—how did your contest go? #leetcode #dsa #java #softwareengineering #competitiveprogramming #problemsolving #learninginpublic #coding
To view or add a comment, sign in
-
Explore related topics
- LeetCode Array Problem Solving Techniques
- Approaches to Array Problem Solving for Coding Interviews
- Solving Sorted Array Coding Challenges
- Why Use Coding Platforms Like LeetCode for Job Prep
- Common Algorithms for Coding Interviews
- Strategies for Solving Algorithmic Problems
- How to Use Arrays in Software Development