👉 LeetCode: 278. First Bad Version This one’s a classic binary search problem that tests how well you understand mid calculations and boundary updates. 👉 Problem: You’re given n versions of a product. One version is bad — and all versions after it are bad too. You need to find the first bad version using the given API isBadVersion(version). Here’s my implementation 👇 public class Solution extends VersionControl { public int firstBadVersion(int n) { int left = 1, right = n; int ans = -1; while (left <= right) { int mid = left + (right - left) / 2; if (isBadVersion(mid)) { right = mid - 1; ans = mid; } else { left = mid + 1; } } return ans; } } 👉 How it works (step by step): 1. Start with the full range from 1 to n. 2. Find the middle version mid. 3. If mid is bad → move left (there might be an earlier bad one). 4. Otherwise → move right. 5. Keep track of the last “bad” version found (ans). 6. When the loop ends, ans holds the first bad version. 👉 Time Complexity: O(log n) Because each check halves the search space. 👉 Space Complexity:O(1) Only a few integer variables are used, no extra data structures. This problem is a neat example of how binary search isn’t just for sorted arrays — it’s a mindset for narrowing down uncertainty efficiently. #LeetCode #Java #Coding #BinarySearch #ProblemSolving
How to find the first bad version using binary search
More Relevant Posts
-
Problem 24 : LeetCode 🚀 LeetCod Solved — Problem #448: Find All Numbers Disappeared in an Array (Cyclic Sort Approach) 🧩 Today, I explored another elegant application of the Cyclic Sort algorithm — solving the classic “Find All Numbers Disappeared in an Array” problem from LeetCode. 🔍 Problem Overview Given an array of integers where 1 ≤ a[i] ≤ n (with n being the array size), some elements appear twice while others appear once. The task: Find all numbers that do not appear in the array, with ⏱️ O(n) runtime 🧠 O(1) extra space 💡 My Approach — Cyclic Sort in Action I used Cyclic Sort for an in-place, efficient solution: In-Place Placement: Each number x should ideally be placed at index x - 1. During iteration, if arr[i] isn’t in its correct position and its target spot isn’t already occupied, I swap the two elements. Missing Number Detection: After sorting, I perform a linear scan — for every index i where arr[i] != i + 1, the missing number is i + 1. ⚙️ Results ✅ Time Complexity: O(n) — Runtime 7 ms, beating 47.63% of Java submissions ✅ Space Complexity: O(1) — Achieved true in-place solution (no extra data structures) ✅ Memory: 67.09 MB — beating 5.95% of submissions 🧩 Tech Stack: Java | Cyclic Sort | Array Manipulation | In-Place Algorithms | DSA Every such problem reinforces my understanding of data placement logic, index manipulation, and memory efficiency — skills essential for writing optimized backend and system-level code. #LeetCode #Java #ProblemSolving #DataStructures #Algorithms #CyclicSort #InPlaceAlgorithm #BackendDevelopment #SpringBoot #DSA #LearningInPublic #CodingJourney Link : https://lnkd.in/d4Z8zTE4
To view or add a comment, sign in
-
-
🔥 Day 122 of My DSA Challenge – Delete Node in a Linked List 🔷 Problem : 237. Delete Node in a Linked List 🔷 Goal : Delete a given node from a singly linked list — but without having access to the head of the list. 🔷 Key Insight : This is one of those classic Linked List interview questions that tests conceptual understanding over coding complexity. Normally, to delete a node, we need access to its previous node (to change the next pointer). But here, we’re not given the head — only the node that must be deleted. So how do we “delete” it? By using a clever trick — 👉 Copy the value of the next node into the current node. 👉 Then skip the next node (effectively deleting it). 🔷 Approach : 1️⃣ Overwrite the current node’s value with the value of its next node. 2️⃣ Link the current node’s next pointer to node.next.next. 3️⃣ This effectively removes the “next” node from the chain, achieving deletion without needing the head reference. Time Complexity: O(1) Space Complexity: O(1) This problem beautifully demonstrates data overwriting and pointer manipulation in linked lists. Sometimes, deleting isn’t about removing — it’s about replacing smartly. ⚡ Concepts reinforced : ✅ In-place modification ✅ Node manipulation ✅ Understanding memory links in Linked Lists Every concept — from arrays to linked lists — builds a deeper sense of logic and problem-solving clarity. #Day122 #DSA #100DaysOfCode #LeetCode #Java #LinkedList #ProblemSolving #Algorithms #DataStructures #CodingChallenge #DeveloperJourney #EngineerMindset #GrowEveryday #Learning
To view or add a comment, sign in
-
-
🌟 Day 28 of #100DaysOfCode 🌟 🔍 Reverse Words in a String — Clean & Elegant String Manipulation 🔹 What I Solved Today, I solved the classic “Reverse Words in a String” problem — a deceptively simple challenge that tests your understanding of string manipulation, trimming spaces, and efficient iteration. This problem is all about cleaning messy input and reordering data logically, which is a valuable skill in real-world text processing tasks. 📝 Problem Statement Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The returned string should have only a single space separating words — with no leading or trailing spaces. Example 1: Input: s = "the sky is blue" Output: blue is sky the Example 2: Input: s = " hello world " Output: world hello Example 3: Input: s = "a good example" Output: example good a 🧠 Concepts Used String Splitting & Trimming Whitespace Handling Iteration & StringBuilder Efficient Memory Management ⚙️ Approach 1️⃣ Trim the string to remove extra leading/trailing spaces. 2️⃣ Split the string by one or more spaces using regex (\\s+). 3️⃣ Iterate backward through the words array. 4️⃣ Append words to a StringBuilder, adding spaces only between words. 5️⃣ Return the final reversed and clean string. 🚀 What I Learned This problem reinforced how attention to detail matters in coding — especially when handling strings and whitespace. It also reminded me that even simple problems can teach clean code principles, edge case thinking, and time-space optimization. Grateful to K.R. Mangalam University for continuously motivating me on this journey of learning and consistency. #100DaysOfCode #Java #ProblemSolving #CodingJourney #DataStructures #Algorithms
To view or add a comment, sign in
-
-
🚀 Day 416 of #500DaysOfCode Problem: 1513. Number of Substrings With Only 1s Platform: LeetCode – Medium Today’s challenge was a classic binary-string problem that focuses on counting substrings composed only of '1' characters. Sounds simple—but with constraints up to 100,000 characters, brute force is impossible. 🔍 What I Learned The key insight is: Whenever you find a continuous streak of 1s of length k, it contributes: k⋅(k+1)2\frac{k \cdot (k+1)}{2}2k⋅(k+1)substrings made only of 1s. Example: 111 → • "1" (3 times) • "11" (2 times) • "111" (1 time) Total = 6 So instead of checking all substrings, we just: ➡️ Count lengths of 1-streaks ➡️ Use the formula ➡️ Keep sum modulo 1e9+7 🧠 Why This Problem Is Useful Builds intuition for pattern-counting in strings Reinforces how mathematical optimization replaces brute-force loops Helps in understanding frequency-based substring logic 📌 Output Examples Input: "0110111" → Output: 9 Input: "101" → Output: 2 Input: "111111" → Output: 21 💡 Reflection Simple logic + clever math = powerful optimization. This problem reminded me how often the pattern matters more than the individual characters. #500DaysOfCode #Day416 #LeetCode #Java #CodingJourney
To view or add a comment, sign in
-
-
🔥 Day 121 of My DSA Challenge – Remove Duplicates from Sorted List 🔷 Problem : 83. Remove Duplicates from Sorted List 🔷 Goal : Given the head of a sorted linked list, remove all duplicate nodes so that each element appears only once, while maintaining the sorted order. 🔷 Key Insight : This problem is a great example of linked list traversal and pointer management. Because the list is already sorted, all duplicates appear consecutively — which makes it easy to detect and skip them in one pass. The challenge is to handle links carefully so that only unique nodes remain connected. 🔷 Approach : 1️⃣ Initialize a dummy node (with a distinct value) to simplify linking. 2️⃣ Use a tail pointer to build a new list containing only unique elements. 3️⃣ Traverse the list using head: If head.val is not equal to the last added node (tail.val), link it. Otherwise, skip the duplicate. 4️⃣ Update tail.next = null at the end to avoid leftover links. 5️⃣ Return dummy.next as the new head. Time Complexity: O(n) Space Complexity: O(1) This problem strengthens concepts of : ✅ Duplicate handling in linked lists ✅ Pointer-based traversal ✅ Clean in-place modification Sometimes, cleaning a data structure is just about connecting only what truly matters. ⚡ Every small pattern makes a big difference in problem-solving clarity. One more concept locked in 💻 #Day121 #DSA #100DaysOfCode #LeetCode #Java #LinkedList #ProblemSolving #Algorithms #DataStructures #CodingChallenge #DeveloperJourney #EngineerMindset #GrowEveryday
To view or add a comment, sign in
-
-
🌟 Day 26 of #100DaysOfCode 🌟 🔍 Remove Duplicate Letters — Lexicographically Smallest Unique String 🔹 What I Solved Today, I tackled the “Remove Duplicate Letters” problem — a fascinating challenge that combines stack operations, greedy logic, and lexicographical ordering. It’s a perfect test of both analytical and implementation skills. 📝 Problem Statement Given a string s, remove duplicate letters so that every letter appears once and only once. You must ensure the resulting string is the smallest in lexicographical order among all possible results. ✅ Example 1: Input: s = "bcabc" Output: "abc" ✅ Example 2: Input: s = "cbacdcbc" Output: "acdb" Constraints: 1 ≤ s.length ≤ 10⁴ s consists of lowercase English letters 🧠 Concepts Used Stack Greedy Algorithm HashMap / Frequency Counting Character Visitation Tracking ⚙️ Approach Count the frequency of each character using a map. Use a stack to build the result string. Iterate through each character: Decrease its frequency (as it’s now visited). If the character is already in the stack, skip it. Otherwise, while the current character is smaller than the top of the stack and the top of the stack will appear later again, pop it out to maintain lexicographical order. Push the current character into the stack. Convert the stack to the final result string. 🚀 What I Learned This problem beautifully demonstrates how greedy thinking and data structures like stacks can work together to maintain order and constraints. It deepened my understanding of how lexicographical optimization problems can be efficiently solved using character frequency and conditional popping. #100DaysOfCode #ProblemSolving #Java #DataStructures #Algorithms #CodingJourney #GeeksforGeeks #KeepLearning
To view or add a comment, sign in
-
-
✨ Two Paths, One Goal: From Patterns to Problems (Day 48) ✨ Today, in collaboration with Chitrang Potdar, we begin a brand-new chapter in our DSA journey — Stacks. After exploring the flexibility of Linked Lists, we now move into a structure that defines order, control, and execution flow — the Stack. 💡 What is a Stack? A Stack is a linear data structure that follows the LIFO (Last In, First Out) principle. The element inserted last is the first one to be removed — just like a stack of plates or books. 🧩 Terminologies: Push → Insert an element onto the top of the stack. Pop → Remove the topmost element. Peek / Top → View the top element without removing it. isEmpty() → Check if the stack is empty. 🏗 Structure of a Stack: Top → [ 30 | 20 | 10 ] → Bottom (New elements are always added and removed from the top.) ⚙️ Importance of Stacks: Simplifies management of nested and sequential tasks. Provides controlled access — only one end is accessible. Backbone of recursion, parsing, and expression evaluation. 🌍 Real-Life Applications: 1️⃣ Undo/Redo operations in editors 2️⃣ Function call management (Recursion Stack) 3️⃣ Backtracking algorithms (Maze, Sudoku) 4️⃣ Expression evaluation and syntax parsing 5️⃣ Browser navigation (Forward/Backward) 🧠 Implementation in Java: We implemented Stacks using: Arrays → Fixed-size, index-based implementation. Linked Lists → Dynamic memory allocation, no fixed limit. 📌 Concepts Covered: Stack fundamentals and LIFO principle Core stack operations (push, pop, peek) Array-based and Linked List-based implementations Real-world significance and use cases 🚀 From tomorrow, we’ll begin working on Stack operations and applications — exploring how logic control and recursion work under the hood. 👉 Swipe for Java code examples. 👉 Don’t miss the Python edition by Chitrang Potdar. #Java #DSA #Stack #TwoPathsOneGoal #PatternToProblem #CodingJourney #LearningByDoing
To view or add a comment, sign in
-
-
🔥 Day 105 of My DSA Challenge – Permutations II 🔷 Problem : 47. Permutations II 🔷 Goal : Generate all unique permutations of a list of integers that may contain duplicates. Example → Input : nums = [1,1,2] Output : [[1,1,2], [1,2,1], [2,1,1]] 🔷 Key Insight : This is a backtracking + deduplication problem — similar to the basic permutation problem, but with an added twist : We must handle duplicates efficiently to avoid generating the same permutation multiple times. 🔷 Approach : 1️⃣ Sort the array to group duplicates together. 2️⃣ Use a boolean vis[] array to track visited elements. 3️⃣ Before choosing a number, skip it if it’s the same as the previous one and the previous one hasn’t been used — this avoids duplicate branches. 4️⃣ Backtrack after each recursive call to explore other paths. 🔷 My Java Approach : Sorted the array to make duplicate detection easier. Used recursion to build permutations step by step. Applied duplicate-skipping condition inside the loop. 🔷 Complexity : Time → O(N! × N) (in the worst case, when all numbers are unique) Space → O(N) (for recursion + visited array) This problem beautifully blends recursion, sorting, and logical pruning, teaching how to handle duplicate elements without extra data structures. Every step in backtracking builds precision — not just in code, but in thinking. ⚡ #Day105 #100DaysOfCode #LeetCode #DSA #Java #ProblemSolving #Backtracking #Recursion #Permutations #CodingChallenge #Programming #SoftwareEngineering #Algorithms #DataStructures #TechJourney #EngineerMindset #DeveloperJourney #Growth
To view or add a comment, sign in
-
-
🚀 Day 52 of #100DaysOfCode 🚀 Today I solved LeetCode Problem #389 – Find the Difference 🧩 This problem is a great example of using ASCII value manipulation to solve what seems like a string comparison challenge. 💡 Key Learnings: Strengthened understanding of character encoding (ASCII values) and how they can simplify logic. Learned how summing character values can help detect differences efficiently without extra data structures. Reinforced the value of O(n) solutions for string-based problems. 💻 Language: Java ⚡ Runtime: 1 ms — Beats 99.32% 🚀 📉 Memory: 41.9 MB — Beats 65.84% 🧠 Approach: 1️⃣ Convert both strings to character arrays. 2️⃣ Compute the sum of ASCII values of both. 3️⃣ The difference between sums gives the ASCII value of the extra character in t. Simple, elegant, and efficient! ⚙️ Sometimes, a clever use of ASCII arithmetic can replace complex logic — efficiency lies in simplicity. #100DaysOfCode #LeetCode #Java #ProblemSolving #CodingChallenge #Algorithms #DataStructures #SoftwareDevelopment #LearningEveryday #CleanCode
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development