</>

704. Binary Search

Easy NeetCode 150
Binary Search Time O(log n) Space O(1)
↗ Open on LeetCode Source: Standard solution only

Quick review

Pattern
Binary Search
Time
O(log n)
Space
O(1)

Standard Solution (C++)

SummaryLocate a target value inside a sorted array and return its index, or -1 if it is absent.

Approach

Classic binary search over the index range.

  • Keep low and high pointers and inspect the midpoint each step.
  • Move the appropriate pointer depending on whether the midpoint value is too small or too large.
  • Use low plus half the gap to compute mid and avoid overflow.
class Solution {
public:
    int search(vector<int>& nums, int target) {
        int lo = 0, hi = nums.size() - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (nums[mid] == target) return mid;
            if (nums[mid] < target) lo = mid + 1;
            else hi = mid - 1;
        }
        return -1;
    }
};
Time O(log n) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern