My easy to understand JAVA solution using binary search

  • 0
    public int firstBadVersion(int n) {
        int result=-1;
        int startIndex = 0;
        int endIndex = n-1;
        while( startIndex<=endIndex ){
            int mid = startIndex+(endIndex-startIndex)/2;
            if( isBadVersion(mid+1) ){
                result = mid+1;
                endIndex = mid-1;
                startIndex = mid+1;
        return result;

    One thing needs to mention is that since isBadVersion API check the version number, need to use mid+1 ( mid is the index, mid+1 is the version number ). The rest part of the solution is pretty straightforward.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.