150NeetCode 150

28.Binary Search

EasyBinary Search ยท 1/7

Problem

You are given an array of integers nums sorted in ascending order (all values distinct) and an integer target. Return the index of target in nums, or -1 if it is not present.

You must write an algorithm with O(log n) runtime complexity.

Examples

Input:  nums = [-1, 0, 3, 5, 9, 12], target = 9
Output: 4
Explanation: 9 exists in nums at index 4.
Input:  nums = [-1, 0, 3, 5, 9, 12], target = 2
Output: -1
Explanation: 2 does not exist in nums.
Input:  nums = [5], target = 5
Output: 0

Constraints

  • 1 <= nums.length <= 10^4
  • -10^4 < nums[i], target < 10^4
  • All integers in nums are unique.
  • nums is sorted in ascending order.

๐Ÿ’ก Key Insight

Because the array is sorted, a single comparison with the middle element tells us which half the target must be in: if nums[mid] < target, everything at or left of mid is too small and can be discarded. Each step halves the search space, so at most log2(n) + 1 comparisons are needed. The whole problem is about getting the loop boundaries exactly right.

Brute Force

TimeO(n)SpaceO(1)

Intuition

Ignore the sorted order and check every index from left to right until we find target.

Algorithm

  1. For i from 0 to n - 1, if nums[i] == target return i.
  2. Return -1.

Visualization

nums = [-1, 0, 3, 5, 9, 12], target = 9

i=0 (-1) โœ—  i=1 (0) โœ—  i=2 (3) โœ—  i=3 (5) โœ—  i=4 (9) โœ“ โ†’ return 4

Code

java
class Solution {
    public int search(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target) {
                return i; // found it
            }
        }
        return -1;
    }
}

Complexity

  • Time: O(n) โ€” in the worst case every element is inspected.
  • Space: O(1) โ€” only a loop index.

Complexity Comparison

Approach Time Space
Brute Force O(n) O(1)
Recursive Binary Search O(log n) O(log n)
Iterative Binary Search O(log n) O(1)

Common Pitfalls

  • Using while (lo < hi) with hi = n - 1 โ€” the last single-element range is never checked, so a target at that position is missed.
  • Writing lo = mid or hi = mid instead of mid ยฑ 1 in this template โ€” when lo == hi - 1 the range stops shrinking and the loop runs forever.
  • Computing mid = (lo + hi) / 2 โ€” fine for this problem's sizes, but lo + hi can overflow int on huge arrays; lo + (hi - lo) / 2 is the safe habit.
  • Forgetting to return -1 after the loop when the target is absent.