← Home

278. First Bad Version

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
binary searchC++Markdown
278

This is one of those problems where the clean idea matters more than the amount of code. For 278. First Bad Version, the solution in this repository is mainly a binary search solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: binary search, two pointers, sliding window.

The notes already sitting in the source point us in the right direction:

  • The API isBadVersion is defined for you.
  • bool isBadVersion(int version);

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are isBadVersion, firstBadVersion.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(logN), space: O(1)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 0 ms, faster than 100.00% of C++ online submissions for First Bad Version.
02//Memory Usage: 6.3 MB, less than 100.00% of C++ online submissions for First Bad Version.
03// The API isBadVersion is defined for you.
04// bool isBadVersion(int version);
05
06class Solution {
07public:
08    int firstBadVersion(int n) {
09        //n is 1-based
10        if(n == 1) return 1;
11        //first -1 to avoid overflow
12        int left = 1, right = n;
13        int mid = left + (right-left)/2;
14        //-1: meaningless, 0: false, 1: true
15        unordered_map<int, bool> cache;
16        // cout << n+1 << " space allocated." << endl;
17        
18        do{
19            // cout << left << ", " << mid << ", " << right << endl;
20            cache[mid] = isBadVersion(mid);
21            if(cache[mid]){
22                //search left part
23                //7->4, 6->3
24                right = mid-1;
25            }else{
26                //search right part
27                left = mid+1;
28
29            }
30            mid = left + (right-left)/2;
31            // if(mid == 1) break; //mid[1-1] is meaningless
32        }while((left <= right) && !(cache.find(mid-1)!= cache.end() && cache.find(mid)!= cache.end() && !cache[mid-1] && cache[mid]));
33        
34        return mid;
35    }
36};
37
38//binary search
39//Runtime: 0 ms, faster than 100.00% of C++ online submissions for First Bad Version.
40//Memory Usage: 6.2 MB, less than 100.00% of C++ online submissions for First Bad Version.
41//time: O(logN), space: O(1)
42// The API isBadVersion is defined for you.
43// bool isBadVersion(int version);
44
45class Solution {
46public:
47    int firstBadVersion(int n) {
48        int left = 1, right = n;
49        while(left < right){
50            int mid = left + (right-left)/2;
51            // cout << left << ", " << mid << ", " << right << endl;
52            if(isBadVersion(mid)){
53                /*
54                when right is equal to left+1, 
55                mid is also left,
56                we should jump out (left < right = mid breaks),  
57                because we have found 
58                the first bad version which is mid, 
59                and mid is equal to left
60                */
61                right = mid;
62            }else{
63                left = mid+1;
64            }
65        }
66        return left;
67    }
68};
69
70//binary seach, different stop condition
71//Runtime: 0 ms, faster than 100.00% of C++ online submissions for First Bad Version.
72//Memory Usage: 5.9 MB, less than 100.00% of C++ online submissions for First Bad Version.
73// The API isBadVersion is defined for you.
74// bool isBadVersion(int version);
75
76class Solution {
77public:
78    int firstBadVersion(int n) {
79        int left = 1, right = n;
80        while(left <= right){
81            int mid = left + (right-left)/2;
82            // cout << left << ", " << mid << ", " << right << endl;
83            if(isBadVersion(mid)){
84                /*
85                when right is equal to left+1, 
86                mid is also left,
87                we should jump out (left = mid <= right = mid-1 breaks), 
88                because we have found 
89                the first bad version which is mid, 
90                and mid is equal to left
91                */
92                right = mid-1;
93            }else{
94                left = mid+1;
95            }
96        }
97        return left;
98    }
99};

Cost

Complexity

Time
O(logN), space: O(1)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.