How to find the first bad version using binary search

👉 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

To view or add a comment, sign in

Explore content categories