← Back to DSA
#704

Binary Search

Easy
ArrayBinary Search
Solve on LeetCode ↗

Binary Search

Why it belongs on this sheet

This is the base template. If you cannot write this quickly and confidently, the later binary-search problems become much harder.

Pattern

Half-interval elimination

Approach

Maintain left and right pointers. Compare the midpoint with the target and discard the half that cannot contain the answer.

Java solution

class Solution {
  public int search(int[] nums, int target) {
    int left = 0;
    int right = nums.length - 1;

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

      if (nums[mid] == target) {
        return mid;
      }

      if (nums[mid] < target) {
        left = mid + 1;
      } else {
        right = mid - 1;
      }
    }

    return -1;
  }
}

Complexity

  • Time: O(log n)
  • Space: O(1)

Interview note

Always know your invariant: the answer, if it exists, stays inside [left, right].