โ† Back to Index

๐Ÿ“š First Bad Version โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

The First Bad Version problem involves finding the first bad version in a sequence of versions, where each version is either good or bad. Once a bad version is found, all subsequent versions are also bad. The goal is to find the first bad version using O(log N) time.

๐Ÿงฑ Pattern Template

public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        int left = 1, right = n;

        while (left < right) {
            int mid = left + (right - left) / 2;

            if (isBadVersion(mid)) {
                right = mid; // Narrow down to the left half
            } else {
                left = mid + 1; // Narrow down to the right half
            }
        }

        return left; // The first bad version
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example: First Bad Version

Input: n = 5, bad = 4
Output: 4

Explanation:
- Versions 1, 2, and 3 are good.
- Version 4 is the first bad version.

๐Ÿ’ก Pro Tips