← Home

704. Binary Search

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
704

The trick here is to name the state correctly, then let the implementation follow. For 704. Binary Search, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. 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: straightforward implementation.

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are bSearch, search.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • 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. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

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(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1.
03
04
05Example 1:
06
07Input: nums = [-1,0,3,5,9,12], target = 9
08Output: 4
09Explanation: 9 exists in nums and its index is 4
10
11Example 2:
12
13Input: nums = [-1,0,3,5,9,12], target = 2
14Output: -1
15Explanation: 2 does not exist in nums so return -1
16 
17
18Note:
19
20You may assume that all elements in nums are unique.
21n will be in the range [1, 10000].
22The value of each element in nums will be in the range [-9999, 9999].
23**/
24
25//Runtime: 72 ms, faster than 91.56% of C++ online submissions for Binary Search.
26//Memory Usage: 27.9 MB, less than 15.64% of C++ online submissions for Binary Search.
27class Solution {
28public:
29    int bSearch(vector<int>& nums, int target, int start, int end){
30        if(end < start) return -1;
31        int mid = (start+end)/2;
32        // cout << mid << endl;
33        if(nums[mid] == target){
34            return mid;
35        }else if(target < nums[mid]){
36            return bSearch(nums, target, start, mid-1);
37        }else{
38            return bSearch(nums, target, mid+1, end);
39        }
40    }
41    
42    int search(vector<int>& nums, int target) {
43        return bSearch(nums, target, 0, nums.size()-1);
44    }
45};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
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.